Here is another LibGDX demo. This one uses Box2D to build a simple model of a box with a gear cog spinning in the centre. If you click on the screen a ball is released which will drop into the view and bounce off the gear and walls. I am no expert in Box2D but I think you may find this useful if you are trying to combine it and LibGDX Scene2D elements.
Few things of note to point out:
- Each body in the world has an associated Actor sprite. I am using an Action to map the position and rotation of each body to the linked Actor. The conversion from Box2D position to pixels is by a conversion factor (the pixel width / the Box2D world width).
- Bodies loaded from the Box2D editor have their position-origin on the bottom left corner. The bodies created from the Box2D ‘primitives’ are positioned at their centre. Handling this inconsistency is a bit of a pain and makes the code a lot less elegant.
- When you close the view (select the BACK key for Android or ESC for Windows) the world is not destroyed, only the balls are marked for removal and subsequent clean-up. When you close the application it will re-claim the memory used.
- There is actually two demos in the source. Under the ‘test’ package you will find a view which uses the LibGDX Box2D debug renderer. You kind of need this to build a ‘world’ before trying to map Scene2D elements to it.
- When you click on the screen fading text is displayed with the pixel co-ordinates. This is just for fun and to show off the sort of things you can do with actions.
Here is a screenshot of the debug rendered ‘world’.
Demo code here.