Skip to content

Instantly share code, notes, and snippets.

@caubry
Last active January 3, 2016 19:19
Show Gist options
  • Save caubry/8507544 to your computer and use it in GitHub Desktop.
Save caubry/8507544 to your computer and use it in GitHub Desktop.
Vec2 = Box2D.Common.Math.b2Vec2;
BodyDef = Box2D.Dynamics.b2BodyDef;
Body = Box2D.Dynamics.b2Body;
FixtureDef = Box2D.Dynamics.b2FixtureDef;
Fixture = Box2D.Dynamics.b2Fixture;
World = Box2D.Dynamics.b2World;
MassData = Box2D.Collision.Shapes.b2MassData;
PolygonShape = Box2D.Collision.Shapes.b2PolygonShape;
CircleShape = Box2D.Collision.Shapes.b2CircleShape;
DebugDraw = Box2D.Dynamics.b2DebugDraw;
RevoluteJointDef = Box2D.Dynamics.Joints.b2RevoluteJointDef;
PhysicsEngineClass = Class.extend({
world: null,
PHYSICS_LOOP_HZ : 1.0 / 60.0,
//-----------------------------------------
create: function () {
gPhysicsEngine.world = new World(
new Vec2(0, 0), // Gravity vector
false // Don't allow sleep
);
},
//-----------------------------------------
update: function () {
var start = Date.now();
gPhysicsEngine.world.Step(
gPhysicsEngine.PHYSICS_LOOP_HZ, //frame-rate
10, //velocity iterations
10 //position iterations
);
gPhysicsEngine.world.ClearForces();
return(Date.now() - start);
},
//-----------------------------------------
registerBody: function (bodyDef) {
var body = gPhysicsEngine.world.CreateBody(bodyDef);
return body;
},
//-----------------------------------------
addBody: function (entityDef) {
var bodyDef = new BodyDef();
var BODY_STATES = {
static: Body.b2_staticBody,
dynamic: Body.b2_dynamicBody
};
bodyDef.type = BODY_STATES[entityDef.type];
bodyDef.position.x = entityDef.x;
bodyDef.position.y = entityDef.y;
var body = gPhysicsEngine.registerBody(bodyDef);
var fixtureDef = new FixtureDef();
if(entityDef.useBouncyFixture) {
this.fixtureDef.density = 1.0;
this.fixtureDef.friction = 0;
this.fixtureDef.restitution = 1.0;
}
var polygonShape = new PolygonShape();
fixtureDef.shape = polygonShape;
fixtureDef.shape.SetAsBox(entityDef.halfWidth, entityDef.halfHeight);
body.CreateFixture(fixtureDef);
return body;
}
//-----------------------------------------
removeBody: function (obj) {
gPhysicsEngine.world.DestroyBody(obj);
}
});
var gPhysicsEngine = new PhysicsEngineClass();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment