Getting Started with Box2D in JavaScript
Written by David Conrad   
Friday, 20 January 2012
Article Index
Getting Started with Box2D in JavaScript
Define a Fixture
A Box For a Ball

Have you ever wondered what Angry Birds uses to obtain its physically realistic range of motions. The answer is Box2D and here we show how to get started with it in JavaScript.a Ideal for the next blockbuster game in a browser.

Box2D is a 2D physics engine.

What this means is that you tell it about a lot of objects and it will simulate how they move. This includes realistic details like gravity, friction, elasticity, jointed bodies, collisions and more.

However, we will start simple and, while it might not be impressive, you will be able to follow how it works and quickly build up to something that is impressive.

If you want to see what sorts of things you can do with Box2D then just checkout any of the many demos. There are also a few successful games that make use of it, including Angry Birds.

The original Box2D was implemented in C++ but it has been ported to a number of other languages. In this article we are going to use a JavaScript port, box2dweb. There are other JavaScript ports and they work in roughly the same way - only the details differ. Indeed the same is true of the different language versions of Box2D and what this means is once you have mastered it in one language you should be able to use it in another - of course you would have to master the other language but this is a small matter.

You might ask, why choose JavaScript as the version to start with?

The simple answer is that there is a lot of scope for using Box2D in the browser now that Canvas support is available and JavaScript is so much faster.

So let's get started.

It is assumed that you know some JavaScript and know how to create a web page. It is also assumed that you have a favourite JavaScript IDE to work with. I'm not going to go into details of how to create a web page or how to edit and debug JavaScript.

This said there is nothing difficult or out of the ordinary in what follows.

Your first task is to download from box2web. In the zip file you will find a full version of box2dweb Box2dWeb-2.1.a.3.js,  a minified version Box2dWeb-2.1.a.3.min.js and two example programs which you can try out.

In most cases you might as well use the minified version of the library so unzip the contents to somewhere suitable and copy Box2dWeb-2.1.a.3.min.js to the same directory as your web page.

Bodies and Fixtures

We don't need a lot of theory but it helps if you know a little Newtonian mechanics. You don't have to know much and as long as you have a rough idea of how the world works the following explanations should be enough.

Box2D is a 2D physics engine which means it computes how things move in 2D and this means that every object has a 2D co-ordinate. It works in the SI system of units which means distances are measured in meters, angles in radians and forces in Newtons.

It is also worth saying that the world coordinate system is mapped into the debug rendering system we are going to use so that 0,0 is at the top left hand corner.

Don't make the mistake of trying to use pixel co-ordinates. In fact we need to go a step further here. Box2D isn't about graphics; it computes the movement of real world objects using world co-ordinates i.e. meters.

Before you panic, there is an easy to use basic graphics rendering function included in the library, but in a real application you would probably want to write your own rendering system.

For this introduction, the built-in debug rendering system is good enough and it is easy to use.

Box2D works with a World object. You then add physical bodies whose motion is simulated on request. There are a number of different variations on a body that you can add to a World, but for this introduction we will just look at a small subset of the possibilities.

A body at its simplest is a point that has a position and a velocity. To give it a shape and other properties you have to add a fixture to it. You can think of this as the body carrying the fixture around as if it was a cutout shape attached to it. So to add, say, a circle to the World you would first have to create a body which sets the position and velocity and then create a fixture with the shape of a circle and attach this to the body.

Define the World

Our example is going to be as simple as possible. All it is going to do is create a circle and let if fall under gravity - later we will make it bounce.

Before we get started we can make our program easier to read and write by setting up some variables that reference the standard objects that we are about to use. If you don't want to do this you don't have to, but it is fairly standard:

function boxdrop() {
var  b2Vec2 = Box2D.Common.Math.b2Vec2
,b2BodyDef = Box2D.Dynamics.b2BodyDef
,2Body = Box2D.Dynamics.b2Body
,b2FixtureDef = Box2D.Dynamics.b2FixtureDef
,b2Fixture = Box2D.Dynamics.b2Fixture
,b2World = Box2D.Dynamics.b2World
,b2MassData =
,b2PolygonShape =
,b2CircleShape =
,b2DebugDraw = Box2D.Dynamics.b2DebugDraw


Notice that all that is going on here is that we are defining variables to use as short names. For example, after these definitions, b2Body can be used in place of Box2D.Dynamics,b2body.

Now our first job is to define the World and there are only two things to specify: gravity and whether it is ok to ignore objects that have come to rest from the point of view of the simulation - which is more efficient.

Gravity is specified as a vector, usually pointing straight down, and standard Earth gravity (i.e. 1g) is 10m/s/s. What all this means is that the standard World is defined by:

world = new b2World(
 new b2Vec2(0, 10)  

The b2Vec2(x,y) function returns a vector pointing in the x,y direction, i.e. an arrow from 0,0 to x,y.

Essentially setting the gravity vector sets what is regarded as up and what is regarded as down in the world.

Notice also that world is a global variable.

Defining a Body

A body has position, velocity and a few other properties. There are also three types of bodies: dynamic, kinematic and static.

  • A static body doesn't move but is recognized as being there by the simulation. You can think of it as an immovable object.
  • A kinematic body moves within the simulation but it is unaffected by forces. Basically it just moves along a trajectory.
  • A dynamic body obeys all of the laws of mechanics and interacts with other bodies.

You generally use dynamic bodies for things that move in the most general way possible and static and kinematic bodies are used as "stage setting".

We need to create a dynamic body for the falling circle but we create a body in two stages - first we create a body definition and then we use this to create the body itself. You can reuse a body definition to create multiple bodies.

The body definition is:

var bodyDef = new b2BodyDef;
bodyDef.type = b2Body.b2_dynamicBody;

and the only other properties we need to set are its x and y positions:

bodyDef.position.x = 10;
bodyDef.position.y =0;

The co-ordinates used will be discussed later but remember they are in meters.

Next we need a fixture to give the body some shape.

Last Updated ( Thursday, 05 January 2017 )