Draw an image on your actor’s Box2D body with libGDX

posted in: Android, Java, libGDX | 0

In this short tutorial, we will see how to correctly draw a textured image attached to a Box2D body with libGDX.

First on our Stage, we have added our Actor. This Actor called in the example “Tile” will contain a box2D.Body named body and a Sprite. It also stores the size of our Box2D body that as a box shape such as:

Note that we initialize the Texture as static so every Tile object will be able to share the same Texture. This is definitely good for the device memory as libGDX is designed for running on Android.

Then we will override the draw function of our Actor.

 

We first set the position of our sprite.

In the setRotation we convert the Box2D radians to degrees angle.

We then set  the origin on where we want to rotate the box, the size of our sprite and just draw it to the batch provided to us by the draw callback.

 

That’s all, we should now have an image that sticks to our Box2D body