Reacting to each other realistically

One of the most complicated and math-intensive components of game development is collision detection and response. If all you need is to calculate when a couple of rectangles overlap, it’s not a big deal, but for games that involve lots of irregularly shaped sprites moving and reacting to each other realistically, you’ll want to use an industrial strength tool to get the job done.

Enter the physics engine.

The idea behind using a physics engine in your game is that instead of hacking together a very-loose approximation of how real objects might interact for your game, dropping in an engine whose sole purpose is to run the physics simulation allows you to leave it to the engine to handle object dynamics and interactions and concentrate on the game itself.

To this end a number of different Physics engines, both 2D and 3D have made their way to JavaScript, many of them ports from other languages, but some written from scratch. For an overview of a number of different engines, take a look at Chandler Prall’s JavaScript Physics Engine Comparison.

Of the myriad of open-source 2D engines that are available, one stands out: Box2D. One reason for this is that it was used as the simulation engine behind mega-hit Angry birds, whose physics-based gameplay required a bullet-proof physics implementation. Box2D is the 2D physics engine of choice for many games, and thus was ported wholesale over to Flash and ActionScript a while back. To get a JavaScript version, some ambitious folks have taken advantage of the similarities between ActionScript and JavaScript and created a converter that converted the ActionScript to JavaScript.

There are a few ports floating about, but the most popular one is Box2DWeb:

Some work has also been done to convert directly from C++ to JavaScript using emscripten (See box2d.js) but this has a different API than box2dweb and doesn’t appear to be kept up.

Box2DWeb doesn’t have it’s own documentation per se, but it shares the same API as the Flash library it was converted from, so the Box2DFlash Documention can be used to figure out the Box2DWeb API. If you’re interested in really diving into Box2D, the official Box2D C++ manual also makes for a worthwhile read, although it contains some newer features not found in Box2DWeb.