Objective
Shows how to create and import a complex Box2D body shape – other than boxes and circles.
Prerequisite:
- Download the free and open source Box2d-Editor tool
- Copy the file BodyEditorLoader.java into your core’s source directory
- Create a Stage and Image Actors (See basic Image Sample)
In this example we create a World using Box2D with gravity.
The gear object is created based on the image below:
Image is imported in Box2d-Editor. Within Box2d-editor draw the vertices around the image. Export your scene as json is copied into our LibGDX project.
In your game load your Json as follow to attach the fixture to the body:
`BodyEditorLoader loader = new BodyEditorLoader(Gdx.files.internal("box2d_scene.json"));`
`BodyDef bd = new BodyDef();`
`bd.type = BodyDef.BodyType.KinematicBody;`
`body = world.createBody(bd);`
`// 2. Create a FixtureDef, as usual.`
`FixtureDef fd = new FixtureDef();`
`fd.density = 1;`
`fd.friction = 0.5f;`
`fd.restitution = 0.3f;`
`// 3. Create a Body, as usual.`
`loader.attachFixture(body, "gear", fd, scale);`
Once done, the Gear object json is loaded and a constant rotation is applied to it.
The balls are generated randomly at the top of the screen so that there is always 100 balls.
The balls are destroyed when they reach the bottom of the screen, which means that new balls are then created.
To detect that the balls have reached the bottom of the screen, a Box Shape body is created there and a ContactListener is added to the world.
Each Body is in its own class which inherit from an Scene2d Image Actor. The actor position and angle is updated based on the Bodies position and Angle.
Code
Full Code available for download here