Physics Engines Comparison

In this article we will take a look at three popular Javascript physics libraries and one that is currently in development: box2dweb, Ammo.js, JigLibJS, and Cannon.js. For each one, a quick introduction will be given and then the library will be rated based on ease of use, performance, and feature set.

Though it is possible to run any of these libraries without a visual representation, that isn’t much fun, so we will set up a small environment to see the results as the simulation runs. I’ll use Three.js and its CanvasRenderer for this due to its popularity and how simple it is to use. Besides showing how the objects are interacting, this will also demonstrate how to extract scene information from each library. The scene will consist of two ramps leading down to a floor; balls will drop down onto the ramps from random locations above the scene, roll down the ramps, and land onto the floor.

Setup

Our base scene that will be used in each example has two ramps which lead down to the ground. Balls will be dropped from random points above the ramps, rolling down to and then off of the ground plane. This simple scene will highlight the similarities and differences between the four libraries.

box2dweb is a port of the C++ box2d project and is unique on our list of libraries in that it is designed to only simulate two-dimensional scenes. All of its classes are namespaced which can make the code a little hard to read, so it is recommended that you create your own local variables for any objects you commonly use. Don’t be fooled into thinking box2dweb is a weak library because it only performs 2D simulations; within its simple API is a ton of power. box2dweb has a full constraint system (which it calls joints), continuous collision detection for more accurate fast-moving bodies, and lots of configuration options both for the whole scene and for individual objects.

Collision detection with box2dweb is easy to do by using the b2ContactListener object. You can have separate event handlers for each of the four collision states: BeginContactEndContactPreSolve, and PostSolve. You can also detect collisions by iterating over the world’s contact list after each step.