Jon Voth [Interactive Specialist]

Adventures in Box2D

At Ham we recently expanded our game framework to include the Box2D physics engine (for AS3). We started down this road while building our latest side-scroller using Actionscript Physics Engine (APE), which was previously the only third-party physics engine integrated into our framework. The trouble was, rectangular shapes in APE were not reacting to applied forces correctly. At this point we decided that instead of finding a quick fix for APE we would take the time to do it right, and incorporate a second physics engine into our framework.

Box2D was a clear choice for this role. Not only is it better documented and supported than APE, it is also vastly more flexible, stable and efficient.

Originally written in C++ by Erin Catto, the version we used was a port to AS3 found here. We ended up using version 2.0.2 as opposed to the most current 2.1, as the documentation, example projects, and many support articles are still written for 2.0.x. There also exists a Cocoa port that may be useful for future iPhone development.

The API for Box2D has several important differences from APE. Most notably, the World object. APE works through a static APEngine object, physics objects are created independently and then added to and removed from the static engine instance. In Box2d the World object handles similar functions, however all physics object are created and destroyed inside the World object for performance optimization purposes. Furthermore, multiple World objects can exist simultaneously, although using this technique should be carefully managed to avoid performance issues.

Similar to physics object creation, collisions are also handled in a centralized manner through the World object. Where one would listen to individual objects for collisions in APE, a Contact Listener object must be used in Box2D and assigned to a World object. From this Contact Listener class it is then possible to notify physics objects and other systems of collisions.

Perhaps the most disorienting difference in Box2D is it’s unit system. Instead of pixels and arbitrary force values, the Box2D system uses the Meters/Kilograms/Newtons system of units. Anything being moved, sized or placed in the Box2D world must be translated into this system and then translated back out to pixels for things like updating a display object’s position based on it’s corresponding physics object. There is a general rule of thumb that 30 pixels equals 1 meter, which we adopted and currently use.

Overall, the transition to Box2D has been a smooth one. We are currently enjoying a sizable performance increase, increased flexibility (with things like object rotation, a variety of joint types, and separate control over mass and density), as well as a wider community and support base.