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.

2 comments:

  1. Thanks a lot man! You saved a lot of time of mine :)

    ReplyDelete
  2. ROBLOX is driven by an ever growing player base of more than 300,000 creators who generate an infinite variety of highly immersive experiences.

    These experiences range from 3D multiplayer games and contests, to interactive adventures where players can take on new identities to discover what it feels to be a dinosaur, a miner in a quarry or an astronaut out in space.

    ReplyDelete