Search code examples
drawinggame-enginelibgdxshapesrectangles

Libgdx - How to draw filled rectangle in the right place in scene2d?


I am using scene2d. Here is my code:

group.addActor(new Actor() {

    @Override
    public Actor hit(float arg0, float arg1) {
        return null;
    }

    @Override
    public void draw(SpriteBatch batch, float arg1) {
        batch.end();
        shapeRenderer.begin(ShapeType.FilledRectangle);
        shapeRenderer.setColor(Color.RED);
        shapeRenderer.filledRect(0, 0, 300, 20);
        shapeRenderer.end();
        batch.begin();
    }
});

The problem is that it draws this rectangular relative to screen (x = 0, y = 0), but I need it to be drawn relative to my group. But if I draw other entities with:

batch.draw(texture, 0, 0, width, height);

it correctly draws at (x = 0, y = 0) relative my group (0,0 pixels from left-bottom corner of the group).

Any suggestions how can I implement shape drawing in scene2d? And can someone can explain why these two calls work differently?


Solution

  • ShapeRenderer has its own transform matrix and projection matrix. These are separate to those in the SpriteBatch that the scene2d Stage uses. If you update the ShapeRenderer's matrices to match those that scene2d is using when Actor.draw() is called then you should get the results that you want.