News Mar 20: R.U.B.E v1.7 released. Instanciable objects!
Feb 21: Added RUBE sample loader for Cocos2d-X v3.4.
Feb 17: Funny Fists released in iOS App store and Google Play store. (YouTube video)
May 25: R.U.B.E v1.6 released. Samplers!
May 12: "On-the-fly" resource updating for Cocos2d-x
Apr 22: New blog post: Inverted pendulum control
Apr 7: On-screen logging class for Cocos2d-x
Mar 22: Downhill Supreme 2 released for iOS and Android
Jan 2: YouTube video: Making soft-body wheels in RUBE
Oct 6: Check out Supplyfront RTS, my 7dRTS entry continued.
Sep 26: R.U.B.E v1.5 released. Customizable item labels, snap-to-grid, export filtering, full-text help search.
Sep 18: Added RUBE sample loader for Cocos2d-X.
Sep 16: Updated RUBE sample loader for Cocos2d v2.
Aug 12: RUBE loader for Nape by Zeh Fernando
Aug 7: Added RUBE sample loader for SFML.
Jul 30: Try my MiniLD 7dRTS entry.
Jul 24: Added physics-driven particles tutorial.
Jul 20: New blog post: rendering solid ground (as in Downhill Supreme)
Jul 18: R.U.B.E v1.4 released. Command-line interface for batch jobs, hotkeys for scripts, better script management.
May 22: Downhill Supreme is out now! (iOS)
Apr 2: R.U.B.E v1.3 released. Collision bitplane editing, Cocos2d-iphone loader, usability improvements.
Mar 11: R.U.B.E v1.2 released. Now supports weld, friction, motor joints and automatic image reloading.
Mar 10: RUBE loader for libGDX by Tim Scott
Jan 28: New blog post: a functional combustion engine!
Jan 22: New blog post: wind tunnel
Jan 20: Added explosions tutorial.
Jan 16: Added buoyancy tutorial.
Jan 16: AndEngine sample project to load RUBE scene by Bart Hirst
Jan 14: R.U.B.E v1.1 released, now supports custom properties.
Jan 1: All basic tutorials are now available in Chinese at Huge thankyou to @OhCoder!
Dec 23: Discussion forums have been set up
Dec 4: R.U.B.E v1.0 is ready !
Dec 2: YouTube video: Box2D pendulum clock
Nov 26: New blog post: rocket platform thingy
Nov 25: Video of R.U.B.E scenes in Chipmunk.
Nov 23: A sample project to load R.U.B.E scenes into Chipmunk physics! Details here.
Nov 14: An XCode sample project to load R.U.B.E scenes on iOS is now available. Details here.
Nov 11: A Java version of b2dJson is now available, based on JBox2D.
Nov 6: A Javascript version of b2dJson based on box2dweb is now available. Demo here!
Nov 2: The full specification of the JSON format used by b2dJson can be found here: b2dJson file structure
Oct 28: YouTube video: 2-minute ragdoll in R.U.B.E Box2D editor
Sep 29: YouTube video: R.U.B.E Box2D editor usage example

Box2D C++ tutorials - World settings

Last edited: July 14 2013

Chinese version -> 中文


Worlds were briefly mentioned in one of the earlier topics as being the main entity in which all the Box2D bodies live. When you create or delete a body, you call a function of the world object to do this, so the world is managing all the allocations for the objects within it too. This means that the world is pretty important, so let's take a look at what we can do with one.
  • define gravity
  • tune the physics simulation
  • find fixtures in a given region
  • cast a ray and find intersected fixtures
The last two of these will be covered in a later topic, so right now we will just look at the first of these, and the life cycle of a world. The testbed framework does this for us, and we've seen it as the m_world class member variable that we have been using, so instead of building a test scene we'll just take a quick look at the way it is done.
A world is set up like any normal class, taking a couple of fundamental settings in the constructor.
  b2Vec2 gravity(0, -9.8); //normal earth gravity, 9.8 m/s/s straight down!
  bool doSleep = true;
  b2World* myWorld = new b2World(gravity, doSleep);
The gravity setting affects every dynamic object in the world, and can be changed later by using SetGravity. For example, try adding this to one of the scenes we made earlier to make a zero-gravity world:
  myWorld->SetGravity( b2Vec2(0,0) );
The sleep parameter says whether bodies should be allowed to 'sleep' if nothing is happening to them, for efficiency. If this is set to true, bodies will sleep when they come to rest, and are excluded from the simulation until something happens to 'wake' them again. This could be a collision from another body, a force applied to it etc.
Note: as of Box2D v2.2.1 the sleep parameter has been removed and defaults to true. To change this you can use b2World::SetAllowSleeping(bool).

Once you have a world created as above, you can add bodies into it as we've been doing. To make anything interesting happen, we need to repeatedly call the Step function of the world to run the physics simulation. This is also being handled by the testbed framework, as part of the Step function of the Test class.
  float32 timeStep = 1/20.0;      //the length of time passed to simulate (seconds)
  int32 velocityIterations = 8;   //how strongly to correct velocity
  int32 positionIterations = 3;   //how strongly to correct position
  myWorld->Step( timeStep, velocityIterations, positionIterations);
In this example, each call to Step will advance the simulation by 1/20th of a second, so a body moving at 5m/s like in our first scene would move 5/20=0.25m in that time. The timeStep also affects how gravity gets to act on each body. You might find that things appear to fall at different accelerations depending on the time step. To make a realistic looking simulation, you will generally set the timeStep value to match the number of times per second you will be calling the world's Step() function in your game. For example in the testbed, the default framerate is 60 frames per second, so Step() is called 60 times a second with timeStep set to 1/60th of a second.

The velocity iterations and position iterations settings affect the way bodies will react when they collide. Typically in Box2D when a collision between two objects is detected, those objects are overlapping (stuck into other) and some calculation needs to be done to figure out how each body should move or rotate so that they are not overlapping any more. Making these values higher will give you a more correct simulation, at the cost of some performance.

(Update 2013/1/20): As requested by Nikolai in the comments, here is some more about what the iterations values actually do, to the best of my knowledge at least.

Firstly, these values are only relevant to collision resolution, so if nothing is colliding then they are not used at all. When two things collide, to resolve the collision (push both bodies so they don't overlap any more) they need to have their position and velocity changed. The need for changing the position should be obvious - this is to correct the overlap. The velocity also needs to be changed, for example to make sure that a ball bounces off a wall correctly, or to make something rotate if it is hit off-center.

The exact details of which body should move where, what their new velocities should be, whether their angular velocity should also be affected etc, is handled by an iterative solver. This means that the calculation does not give you a perfect result the first time, but each time you do it the result gets more accurate. Probably the simplest example of iterative solving is the Newton-Raphson method for finding the roots of a function. Here is a nice animated gif showing this procedure (if you are not familiar with 'finding roots', it just means finding the point where the blue function line crosses the x-axis).

As you can see in the animated gif, the same calculation is done over and over, and each time the solution gets closer to the exact result. Typically you would stop doing this calculation when the result does not change much anymore, because that means you are so close to the solution that doing more iterations does not improve the answer. If your calculation time is limited, you could stop doing the calculation after a fixed number of iterations, even though the answer you get is not an exact solution.

Typically Box2D is used for fast-paced simulations where an exact solution is not necessary, and at 60 frames per second it's hard to see little imperfections anyway. So we usually want to set an upper limit on how many iterations to do, to keep the CPU time required reasonable.

One way to decide on a good balance of these values for your situation would be to start by setting them really low, even as low as 1 may sometimes be ok for sparse simulations. If you have fast collisions, or many things touching each other all at the same time (especially piles and stacks of bodies) you will need to raise these values to avoid having things penetrating each other and making things look sloppy. At some point, you will find that raising the values further doesn't really help anything.

One last point to note is that these values are only an upper limit. If Box2D decides that the solution it has is good enough, it will stop calculating without using all the iterations you have allowed it. So even if you set these to say, 50, that does not mean it will always take ten times longer than setting it to 5. It only means that in a demanding case (like a big stack of blocks) you have given it permission to take ten times as long. This means that your game could run nice and smooth, until you get a huge pile of things stacked up and then it mysteriously starts to get slow and choppy, so you should check that the values you set will perform ok for all cases that your game is likely to encounter.

Cleaning up

When you're done with a world object, delete it as normal:
  delete myWorld;
When a world is destroyed like this, it takes care of deleting all the joints and bodies in it. Remember not to use the deleted body pointers after this!

Not seeing the any comments below? Try changing the 'https' in the page URL to just 'http'
Click here: