My favorites | Sign in
Project Home Downloads Wiki Issues Source
Search
for
BasicUsage  
differences between Box2dFlash and Box2dWeb
Updated Feb 20, 2011 by Uli.He...@googlemail.com

Introduction

For basic usage of Box2D, you should read the documentation of the original C++ version: http://www.box2d.org/manual.html

Box2dWeb is organized the same way as Box2dFlash. I.e. the API is almost identical. You can find the documentation here: http://www.box2dflash.org/docs/2.1a/reference/

Anyways, there are some differences which are documented on this page.

Importing Classes

There is no way to import packages and classes in Javascript, so you have to use var assignments, if you don't want to use full addresses.

The code below demonstrates my recommendation how to write Javascript in general, because the global scope is not polluted. This increases performance, because the Javascript engine doesn't need to traverse the whole scope-chain when looking up your definitions. It also contains the assignments which are most commonly used when starting a new project, so you can copy and paste it.

(function() {

   var b2Vec2 = Box2D.Common.Math.b2Vec2;
   var b2BodyDef = Box2D.Dynamics.b2BodyDef;
   var b2Body = Box2D.Dynamics.b2Body;
   var b2FixtureDef = Box2D.Dynamics.b2FixtureDef;
   var b2Fixture = Box2D.Dynamics.b2Fixture;
   var b2World = Box2D.Dynamics.b2World;
   var b2MassData = Box2D.Collision.Shapes.b2MassData;
   var b2PolygonShape = Box2D.Collision.Shapes.b2PolygonShape;
   var b2CircleShape = Box2D.Collision.Shapes.b2CircleShape;
   var b2DebugDraw = Box2D.Dynamics.b2DebugDraw;
   

})();

Debug Drawing

Although Box2D is a physics engine and therefore has nothing to do with drawing, Box2dFlash provides such methods for debugging which are defined in the b2DebugDraw class. In Box2dWeb, a b2DebugDraw takes a canvas-context instead of a Sprite:

var debugDraw = new Box2D.Dynamics.b2DebugDraw;
debugDraw.SetSprite(document.GetElementsByTagName("canvas")[0].getContext("2d"));

Working with Events

You have to implement event-interfaces in Box2dFlash. Since Javascript doesn't support classical inheritance natively, I show you how to deal with events in Box2dWeb:

var world = new Box2D.Dynamics.b2World(new Box2d.Common.Math.b2Vec2(0, 10), true);

/* ... add bodies, etc. ... */

var myListener = new Box2D.Dynamics.b2DestructionListener;

myListener.SayGoodbyeFixture = function(fixture) {
   alert("goodbye fixture ...");
}

world.SetDestructionListener(myListener);
Comment by bart.bur...@gmail.com, Jan 13, 2011

How can I set a listener when objects hit each other? For example I want to implement a score counter.

Comment by project member Uli.He...@googlemail.com, Jan 13, 2011

You need a contact listener. The Box2D documentation explains how to use it. I'll add a link on the wiki page.

Basically:

var contactListener = new Box2D.Dynamics.b2ContactListener;
contactListener.BeginContact = function(contact, manifold) {
   //do some stuff 
};
world.SetContactListener(contactListener);
Comment by danie...@bestcoolfungames.com, Feb 17, 2011

"Javascript doesn't support object-oriented programming natively" is a overstament. Just because support OO with classes (or does it? see coffeescript for more on this), and uses OO with prototype, it does not mean it is not OO.

To see how easy it is to implement interfaces (actually Traits, which are like Scala's traits, a more powerful interface kind) you can see this project: rbcoffee

Comment by project member Uli.He...@googlemail.com, Feb 20, 2011

You're right. I changed it to "doesn't support classical inheritance (...)".

Comment by dan...@gmail.com, Feb 21, 2011

Great! Also, I'd make a reference to the manual as well. It essentially solved my issue of Drawing Sprites (it says it by using the naive algorithm, which is probably fine if you are in a scene with lots of moving objects, as they will all have to be redrawn any way, so any algorithm that uses less than O(elements of the scene) will not be better than O(elements that changed position since last step)).

Comment by dan...@gmail.com, Feb 22, 2011

Quick note: due to coffeescript's deestructuring assignment, the import above can be written in only 4 readable lines:

b2Vec2 = Box2D.Common.Math.b2Vec2
b2AABB = Box2D.Collision.b2AABB
{b2BodyDef, b2Body, b2FixtureDef, b2Fixture, b2World, b2DebugDraw} = Box2D.Dynamics
{b2MassData, b2PolygonShape, b2CircleShape} = Box2D.Collision.Shapes
Comment by dan...@gmail.com, Feb 23, 2011

The sprite's link point to an old wiki (which hidden inside the original project's wiki as a zip file). I've made it public as a gist here

Comment by aaron%cu...@gtempaccount.com, Mar 24, 2011

I've been having some trouble getting joints to work. I'll give an example of a revolute joint that's not working for me. My Javascript error console gives me a TypeError?: The result of expression 'xf1' undefined? is not an object. Box2D.js 7533

Here's the code that creates the objects and joint. Thanks for any help!

var bodyDef = new b2BodyDef;
bodyDef.type = b2Body.b2_dynamicBody;
var fixDef = new b2FixtureDef;
fixDef.shape = new b2PolygonShape;
fixDef.shape.SetAsBox(120/drawScale, 45/drawScale);
fixDef.restitution = 0;
fixDef.friction = 0.2;
fixDef.density = 0.2;
bodyDef.position.Set(399.65/drawScale, 464.8/drawScale);
bodyDef.angle = 0;
fixDef.filter.categoryBits   = 0x0002;
fixDef.filter.maskBits       = 0x0001;
var dynamicBody = world.CreateBody(bodyDef).CreateFixture(fixDef);

var bodyDef = new b2BodyDef;
bodyDef.type = b2Body.b2_staticBody;
var fixDef = new b2FixtureDef;
fixDef.shape = new b2PolygonShape;
fixDef.shape.SetAsBox(116.2/drawScale, 83.5/drawScale);
fixDef.restitution = 0;
fixDef.friction = 1;
fixDef.density = 1;
bodyDef.position.Set(399.65/drawScale, 504.55/drawScale);
bodyDef.angle = -1.5707963267948966;
fixDef.filter.categoryBits   = 0x0002;
fixDef.filter.maskBits       = 0x0001;
var staticBody = world.CreateBody(bodyDef).CreateFixture(fixDef);

var revJointDef = new b2RevoluteJointDef;
revJointDef.bodyA = dynamicBody;
revJointDef.bodyB = staticBody;
revJointDef.anchor = new b2Vec2(399.65/drawScale, 464.8/drawScale);
revJointDef.collideConnected = true;

revJointDef.maxMotorTorque = 5.0;
revJointDef.motorSpeed = 0.0;
revJointDef.enableMotor = true;

var revJoint = world.CreateJoint(revJointDef);
Comment by aaron%cu...@gtempaccount.com, Mar 29, 2011

Would someone be willing to post one or more basic joint examples? I've been using Box2D and Box2D Flash for a while now, but can't seem to get joints to work with Box2DWeb. Thanks!

Comment by project member Uli.He...@googlemail.com, Mar 30, 2011

var dynamicBody = world.CreateBody?(bodyDef).CreateFixture?(fixDef);

These kind of assignments won't work, since CreateFixture?() doesn't return the body, but the created fixture ;)

Comment by aaron%cu...@gtempaccount.com, Mar 30, 2011

Thanks, fishbone! I knew it would be something simple like that :)

Comment by alo...@gmail.com, Apr 26, 2011

I'm getting a weird: 'undefined' is not an object (evaluating 'other.lowerBound') When I try to do a world.step(); It looks like "other" in the "b2AABB.prototype.TestOverlap? = function (other){...}" is null, any ideas? :S

I'm using Objective-J but it should look very familiar to you guys. Here is the code: https://gist.github.com/943779

All objects have a valid starting position and a force.

Comment by andrea.d...@gmail.com, May 16, 2011

I'm trying to combine two shapes, but the only example that does this uses "ballBd.AddShape?(ballSd1);" so I think it is an obsolete version. I've searched for "combined" or "compound" in the documentation, but could not fine anything useful.

Any two-lines example would be great!

Comment by Jonathon...@gmail.com, Jun 21, 2011

Hey all,

I am trying to create and implement a Distance Joint in a world.

Creating it was easy, as I've used older versions of Box2D.js. However when I added the joint to the world, my bodies render, but the joint doesn't and I receive the error Uncaught TypeError?: Cannot read property 'position' of undefined which stems from world.DrawDebugData?()

Any ideas? Thanks.

var fixDefOne = new b2FixtureDef;
fixDefOne.density = 1.0;
fixDefOne.friction = 0.5;
fixDefOne.restitution = 0.2;
	 
var bodyDefOne = new b2BodyDef;
	 
//create some objects
bodyDefOne.type = b2Body.b2_dynamicBody;
fixDefOne.shape = new b2CircleShape(Math.random() + 0.1);
bodyDefOne.position.x = Math.random() * 10;
bodyDefOne.position.y = Math.random() * 10;
world.CreateBody(bodyDefOne).CreateFixture(fixDefOne);
	 
var fixDefTwo = new b2FixtureDef;
fixDefTwo.density = 1.0;
fixDefTwo.friction = 0.5;
fixDefTwo.restitution = 0.2;
	 
var bodyDefTwo = new b2BodyDef;
	 
//create some objects
bodyDefTwo.type = b2Body.b2_dynamicBody;
fixDefTwo.shape = new b2CircleShape(Math.random() + 0.1);
bodyDefTwo.position.x = Math.random() * 10;
bodyDefTwo.position.y = Math.random() * 10;
world.CreateBody(bodyDefTwo).CreateFixture(fixDefTwo);
	 
var disJDef = new b2DistanceJointDef();
	 
disJDef.bodyA = bodyDefOne;
disJDef.bodyB = bodyDefTwo;
disJDef.dampingRatio = 0.7;
disJDef.frequencyHz = 0.2;
disJDef.collideConnected = true;
disJDef.localAnchorA = new b2Vec2(bodyDefOne.position.x,bodyDefOne.position.y);
disJDef.localAnchorB = new b2Vec2(bodyDefTwo.position.x,bodyDefTwo.position.y);
world.CreateJoint(disJDef);
Comment by newe1...@gmail.com, Nov 6, 2011

Hi Jonathon,

I have this code:

// up above
var fixDef = new b2FixtureDef;
         fixDef.density = 1.0;
         fixDef.friction = 0.5;
         fixDef.restitution = 0.2;
         
         
         var bodyDef = new b2BodyDef;


// then down below

        fixDef.shape = new b2CircleShape(.6);
        bodyDef.position.x = 12;
        bodyDef.position.y = 5;
        fixDef.userData = {
            color: 'blue',
            removeMe: false,
            letter: 'g',
            image: littleGOverlay, 
            type: 'letter'
        };
        
        // .CreateFixture(fixDef)
        var topg = world.CreateBody(bodyDef);
        topg.CreateFixture(fixDef);
        
        fixDef.shape = new b2CircleShape(.6);
        bodyDef.position.x = 12;
        bodyDef.position.y = 6;
        fixDef.userData = {
            color: 'blue',
            removeMe: false,
            letter: 'g-sub',
            image: littleGOverlay, 
            type: 'letter'
        };
        
        // .CreateFixture(fixDef)
        var bottomg = world.CreateBody(bodyDef);
        bottomg.CreateFixture(fixDef);
        
        var jointDef = new b2DistanceJointDef();
        var worldAnchorOnBody1 = new b2Vec2(12, 5);
        var worldAnchorOnBody2 = new b2Vec2(12, 6);
        jointDef.Initialize(topg, bottomg, worldAnchorOnBody1, worldAnchorOnBody2);
        jointDef.collideConnected = true;
        world.CreateJoint(jointDef);

And the joints work here. I think it might have something to do with the debug data setup?

At the minimum make sure you include:

var debugDraw = new b2DebugDraw();
             debugDraw.SetSprite(document.getElementById("canvas").getContext("2d"));
             debugDraw.SetDrawScale(30.0);
             world.SetDebugDraw(debugDraw);

in your debug definition...

Comment by Rv.mak...@gmail.com, Jan 22, 2012

Sorry but in the example you made mistake:

var debugDraw = new Box2D.Dynamics.b2DebugDraw;
debugDraw.SetSprite(document.GetElementsByTagName("canvas")[0].getContext("2d"));

document object don't have method GetElementsByTagName?, but has getElementsByTagName.

Maksim

Comment by ch...@netsmith.co.uk, May 2, 2012

Can anyone point me at an example or tutorial which simply drops square images down a screen under gravity where they collide with each other.

Thanks

Comment by iforc...@gmail.com, Sep 12, 2012

fwiw there are some nice box2dweb tutorials here: http://codingowl.com/

Comment by nuigurum...@gmail.com, Oct 29, 2012

I have a problem with revolute joints keep stretching. I've tried asking on stackoverflow already, but to no avail. I've tried playing with density and b2MassData, it seem to affect the degree of stretching, but nonetheless the joints stretch more and more and more, until everything seem broken already, and then even more. What could be the reason? Just a little stretching wouldn't be a problem, the problem is that it accumulates. I have nearly exactly same code made for older box2djs, and there is no such problem...

Comment by hyzh...@gmail.com, Mar 31, 2013
Comment by lufy.leg...@gmail.com, Dec 26, 2013

Hi,I am lufy. there is a sample for box2dweb http://lufylegend.com/demo/AngryBirds

Comment by webdesig...@gmail.com, Dec 30, 2013

How do you destroy bodies without leaking memory with Box2D web? see my question here (contains code and screenshots): http://stackoverflow.com/questions/20817760/how-to-properly-delete-a-box2d-body-in-version-box2dweb-2-1-a-3-box2d-v2-3-1r3


Sign in to add a comment
Powered by Google Project Hosting