Sunday 26 October 2014

J/Box2D first steps

I came across to use JBox2D and I didnt know anything about how a physical engine works, so I am writing some helpful tips here.

Scale and dimensions

Firstable you have to keep on your mind that Box2D works with meters, so forget pixel or dpi, you will need to use some functions to convert these measurements to something that the engine can understand.
In general people use a scale, because the engine works in a world of 100x100 meters, so its better to have it as small as possible. The common scale is 30.

Here a simple way to convert pixel to Box2D dimensions:


Create a simple ball

Let's start with the second step, you have to define all properties of the object, if its a ball, it has to have  round shape and be elastic.

So you have to define the body definition, if the object will be static or dynamic  and set the position in the world:


The position might be tricky to understand, but here is a simple solution:
When you want to draw something in a canvas, you draw something from position (X,Y), so if you want to draw something at the top left corner, you will choose (0,0).
So in this thinking you would put new Vec2(0,0) in this case, but this will be WRONG because in Box2D everything works in another way, you have to tell the position of the centre of the object.

If you object is  10x10 and you want to position to the top left corner, you position will be (5,5).

To continue the body creation, you have to tell the world that this object exists in the engine, so you have to call the method "createBody"


Then tell at the body, what kind of shape your object will be:


In this case we create a CircleShape, because its a ball. In other case you have to use PolygonShape to create a special shape or a simple square.

Another tricky to understand how to create a PolygonShape for a square is the follow:

You have to use "setAsBox", and the dimension that you put inside must to be half of the width and half of the height, because the BodyDefinition has the position of the centre of the object.

Last thing to complete the creation of the ball in the world is the Fixture Definition:


You can change the density, that is the weight of the object, the friction between objects and the restitution that is the elasticity. Play with some values and you will find out what better works with your project.

Joints

Joints are parts that connects two body parts, there are different ones.
There is a joint to simulate a rope connection, an elastic connection, a rotation connection, etc...
You can find more information around in the web, it is very simple to use them but tricky to find the right values or anchor points.