Adding Physics with Box2D

A bunch of static elements hanging out in space isn’t a whole lot of fun. To make things more interactive and save the hassle of trying to figure out collisions on arbitrary convex polygons, Quintus adds support for a JavaScript port of a well-known 2-D physics engine called Box2D, which is available at: http://box2d.org/.

Box2D, created by Erin Catto, is written in C++, but a few adventurous souls manually created an ActionScript 3.0 port called Box2DFlash (available at http://box2dflash.sourceforge.net/) to allow Flash developers to use Box2D. A few other adventurous folks, taking advantage of the similarities between ActionScript and JavaScript, created an ActionScript to JavaScript converter that could convert the ActionScript code to JavaScript. Got all that?

The easiest to use and most up-to-date JavaScript port is currently box2dweb, available on Google Code: http://code.google.com/p/box2dweb/.

Although it’s not a perfect fit for the JavaScript environment because Box2web creates a lot of objects each frame and so can challenge the JavaScript garbage collector, it works surprisingly well, and integrating it with the SVG code already written is straightforward.

There is no full documentation for Box2Dweb, but that’s because it shares the same definitions as box2dflash, which has good API documentation: www.box2dflash.org/docs/2.1a/reference/.

The SVG code in this chapter was implemented specifically with the idea to add in a physics engine, but it ...

Get Professional HTML5 Mobile Game Development now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.