Wednesday, 21 December 2011

JBox2D Tutorial : Simulating JBox2D world

In previous post we have learned how to create JBox2D world. We also learned how to create bodies and add them to the world. Now next step is to simulate the JBox2D world.

To simulate the world, we need to call step method of the world.

float timeStep = 1.0f / 60.f;
int velocityIterations = 6;
int positionIterations = 2;

for (int i = 0; i < 60; ++i) {
world.step(timeStep, velocityIterations, positionIterations);
      Vec2 position = body.getPosition();
      float angle = body.getAngle();
      System.out.printf("%4.2f %4.2f %4.2f\n", position.x, position.y, angle);
}
As you can see in above snippet, we are passing three arguments to the world.step

timeStep - This defines how much simulation should advance in one second. In above example simulation will advance by 1/60th second on every call to the step method.

velocityIterations – This define how accurately velocity will be simulated. Higher iteration value increases the accuracy of velocity simulation but decreases the performance. The recommended velocity iteration value is 6.

 positionIterations – This is similar to velocity iteration, higher value means more accurate position simulation but lesser performance. The recommended position iteration value is 3.

In above sample code snippet on every simulation step we are getting body’s new position and angle details and printing them to the console. So far we have learned about world, bodies and world simulation. In next post we will write our first JBox2D program with JavaFX 2.0

<<Creating Body                                      Writing first JBox2D program>>

3 comments:

  1. Where to put this code snippet!?

    ReplyDelete
    Replies
    1. in an update() function of your program or any function that get's updated every second.

      Delete

There was an error in this gadget