Question : In the following snippet, I wish to draw different shapes such as rectangles, circles, triangles etc. I will be creating different class files for each of such objects, as I did for Rectangle class here.
I've been trying to invoke the draw method of Rectangle object from Stage object, but I am unable to do so. If I make a plain call to the draw method of the Rectangle object, I can draw the object.
Can some one suggest me how is this possible ? Also, I had many other queries which I'd tried to put in comments. Please have a look at them and kindly help me in figuring out the concept beneath it.
Disclaimer : I am new to game programming, started with Libgdx.
Following is the Scan class :
package com.mygdx.scan.game;
import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer.ShapeType;
import com.badlogic.gdx.scenes.scene2d.Stage;
public class Scan extends ApplicationAdapter {
private Stage stage;
public static ShapeRenderer shapeRenderer;
@Override
public void create () {
stage = new Stage();
shapeRenderer = new ShapeRenderer();
Rectangle rect1 = new Rectangle(50, 50, 100, 100);
stage.addActor(rect1);
}
@Override
public void render () {
Gdx.gl.glClearColor(1, 1, 1, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
shapeRenderer.setProjectionMatrix(stage.getCamera().combined);
shapeRenderer.begin(ShapeType.Filled);
shapeRenderer.setColor(Color.BLACK);
//new Rectangle(50, 50, 100, 100).draw();
shapeRenderer.end();
// This should call Rectangles draw method. I want a Shapetype.Filled Rectangle.
// But I'm unable to invoke this method if I add the actor in stage object and invoke it's draw method.
stage.draw();
}
public void dispose() {
stage.dispose();
}
}
Following is the Rectangle Actor class :
package com.mygdx.scan.game;
import com.badlogic.gdx.scenes.scene2d.Actor;
public class Rectangle extends Actor {
float xcord, ycord, width, height;
public Rectangle(float x , float y , float width, float height) {
this.xcord = x;
this.ycord = y;
this.width = width;
this.height = height;
}
// This needs to be called in the Scan class. I just want the draw method to be invoked.
// Also I wish to draw many such rectangles. What is the best practice to get hold of ShapeRenderer object from Scan class ?
// Should I use one instance of ShapeRenderer object in Scan class or should I create ShapeRenderer object for each of the Rectangle object ??
// I also plan to repeat the activity for another object such as circles. So I would like to know the best practice here.
public void draw() {
Scan.shapeRenderer.rect(this.xcord, this.ycord, this.width, this.height);
}
}