Left-click to create an object. Right-click to show next example.

What's this

Box2DJS is a JavaScript port of Box2D Physics Engine. To tell the truth, this is converted from Box2DFlashAS3_1.4.3.1 in an automatic manner. (The reason why not Box2DFlashAS3_2.0.0 based is simply because I overlooked the renewal.)

How to use

  1. Download a zip file and extract it.
  2. Copy js/ and lib/ directories from the extracted directory to your app directory.
  3. Copy script tags in the header part of index.html in the extacted directory to your html file where you want to simulate physics.

    Because this libray does not have a lazy-loading system now, you should load all classes before starting your simulation. To make things worse, each library has a bit complecated dependency each other so that loading libraries in wrong order may cause a fatal error. To avoid such a trouble, it is strongly recomended to copy the header part of this file or `index.html' including the downloaded zip file.

  4. Utilizing Box2D APIs, simulate the newton world as you like.

    The Box2DJS APIs are completely same as those of Box2DFlashAS3. Please refer information about it.

Sample code

Create a world

var worldAABB = new b2AABB();
worldAABB.minVertex.Set(-1000, -1000);
worldAABB.maxVertex.Set(1000, 1000);
var gravity = new b2Vec2(0, 300);
var doSleep = true;
var world = new b2World(worldAABB, gravity, doSleep); 

Create a circle body

var circleSd = new b2CircleDef();
circleSd.density = 1.0;
circleSd.radius = 20;
circleSd.restitution = 1.0;
circleSd.friction = 0;
var circleBd = new b2BodyDef();
circleBd.AddShape(circleSd);
circleBd.position.Set(x,y);
var circleBody = world.CreateBody(circleBd);

Create a revolute joint

var jointDef = new b2RevoluteJointDef();
jointDef.anchorPoint.Set(250, 200);
jointDef.body1 = world.GetGroundBody();
jointDef.body2 = circleBody;
world.CreateJoint(jointDef);

Step a world

var timeStep = 1.0/60;
var iteration = 1;
world.Step(timeStep, iteration);

Repeat stepping (for instance)

var ctx;
var canvasWidth; 
var canvasHeight; 
function step(cnt) {
  world.Step(1.0/60, 1);
  ctx.clearRect(0, 0, canvasWidth, canvasHeight);
  drawWorld(world, ctx); // see demos/draw_world.js
  setTimeout('step(' + (cnt || 0) + ')', 10);
}
Event.observe(window, 'load', function() {
  setupWorld(world); // as you like
  ctx = $('canvas').getContext('2d');
  var canvasElm = $('canvas');
  canvasWidth = parseInt(canvasElm.width);
  canvasHeight = parseInt(canvasElm.height);
  step();
});

Dependencies

  • prototype.js
  • IECanvas (when you use a canvas tag to display the result of your physics simulation)

Links

Contact

If you have some requests or find any bugs, please tell me about them.

E-mail: andyjpn _at_ gmail _dot_ com
Blog: http://d.hatena.ne.jp/technohippy/ (written in Japanese)