Creating a Box2D World
This article is meant for advanced and expert coder so I will not
show how to import classes or write functions or classes. You are
assumed to know all this already.
We will be working with a simple document class for this tutorial. Assuming you downloaded the latest Box2D (2.1a), let’s get started.
Creating our world:
The b2Vec2 vector is setting the gravity system. You can of course experiment with different gravity system. Now we need to update our world on a constant basis so let’s just use a Timer for that. I set the timer to 33ms which is close to 30fps.
world.Step(1 / 30, 10, 10);
And here we go. We do have a Box2D world working properly. Pretty easy right? Note the step method, first value is the time step, that is how much time has passed in between each step. Second value is the velocity iteration, and third is the position iteration. Box2D loops roughly through all objects and calculate their position and velocity. Those two iteration values determine how many time box2D will perform those calculation. The more iteration, the more accurate will be the results but also of course the more CPU Box2D will be using. Yes, that means with lower values box2D might miss some collision or position incorrectly some objects.
You should call ClearForces() after each time step as required by Box2D.
Of course it’s not that exciting since there’s nothing to see but our 2D world simulation is actually already working. To prove it here’s a little demo, just click anywhere and see the Box2D circle falling.
Experiment with different gravity values, different time steps to get a good understanding of those.
What you are actually seeing here is the box2D debug mode which is the next subject .