简体   繁体   中英

How to render multiple Shapes in Libgdx?

I created a bunch of rectangles using for loop and then added them to an array list. I taught that the rendering would be similar the way you render userdata from box2d.

sr.setProjectionMatrix(camera.combined);
sr.begin(ShapeRenderer.ShapeType.Filled);
    for(Rectangle r : rectangles)
          sr.rect(r.x, r.y, r.width, r.height);

sr.end();

the problem is that after the fro loop is over, the rectangles are not being rendered anymore, I know that this is happening because you are not rendering the actual rectangle but just using shapeRenderer to draw a shape using the attributes of the rectangles. Is there a way to do this that is similar the way you render a sprite?

In LibGDX, the Sprite class is specifically designed for rendering with a SpriteBatch. It contains an actual array of data that can be copied directly into SpriteBatch's Mesh data array. That is the reason it has it's own draw method, unlike TextureRegion. This backing data array in Sprite gives it the potential for faster drawing, because some of its data only has to be recalculated if it moves.

ShapeRenderer does not provide any way to directly pass a Mesh vertex data array. And the Rectangle class is not designed specifically for rendering. If you are simply looking for an easier way to write drawing code, you could subclass Rectangle to add a convenience method for drawing it directly with a ShapeRenderer.

public class MyRectangle extends Rectangle {

    //... constructors

    public void draw (ShapeRenderer shapeRenderer){
        shapeRenderer.rect(x, y, width, height);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM