Showing posts with label box2dweb. Show all posts
Showing posts with label box2dweb. Show all posts

Sunday, October 27, 2013

Box2dWeb dynamic objects pass through some static bodies

While making a little game, I ran into an issue when using polygons where some moving objects would collide with a static body and slowly move through it as if it were a dense medium. This issue did not occur when the static body was created with the SetAsBox method. When creating a shape as a box, the moving objects bounced off correctly.

var slantFixtureDef = new b2FixtureDef;
slantFixtureDef.density =     1.0;
slantFixtureDef.friction =    0.5;
slantFixtureDef.restitution = 0.2;
slantFixtureDef.shape = new b2PolygonShape;
slantFixtureDef.shape.SetAsBox(10, 1);

What I really wanted was to use vertices for this shape so that I could rotate it how I wanted.
var points = [
    {x: 0, y: 0},
    {x: 0, y: 0.5},
    {x: 5, y: 0.5},
    {x: 5, y: 0}
];

var vecs = [];
points.forEach(function(e, i, arr) {
    var vec = new b2Vec2(e.x, e.y);
    vecs[i] = vec;
});

slantFixtureDef.shape.SetAsArray(vecs, vecs.length);

But creating a shape like this caused the problem of dynamic bodies not bouncing off this static body. The issue turned out to be that the vertices were specified in the wrong order. Box2dWeb requires you to specify the vertices in clockwise order even though the C++ version requires counter-clockwise order.
var points = [
    {x: 0, y: 0},
    {x: 5, y: 0},
    {x: 5, y: 0.5},
    {x: 0, y: 0.5}
];

Simple as that!

Monday, October 21, 2013

Box2dWeb: b2World is not defined

As I was playing around with a javascript physics engine called Box2dWeb. Almost immediately I ran into an issue. I was receiving the error in Chrome console:

Uncaught ReferenceError: b2World is not defined

This occurs because the objects from this library have a "namespace". Well, actually, there are no namespaces in javascript, but the methods are stored in different objects. To resolve this issue, all you have to do is make aliases for these methods, or in other words, make short local variables for the full methods.

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

The author actually recommends this in the documentation. The idea behind the author's suggestion is putting the variables into the scope of the function to improve speed so that the browser doesn't have to search all the scopes.