Created
July 17, 2012 17:12
-
-
Save Synvox/3130641 to your computer and use it in GitHub Desktop.
Physics
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function Physics(args) { | |
var pixelsPerMeter=args.ptm; | |
function px(x){ | |
return x*pixelsPerMeter; | |
} | |
function meters(x){ | |
return x/pixelsPerMeter; | |
} | |
function Body(args) { | |
var self = Class({ | |
b2Body:args.body, | |
physics:args.physics, | |
init: function() { | |
return self; | |
}, | |
bodyType:args.bodyType, | |
shapeType:args.shapeType, | |
get x() { | |
return px(self.body.GetPosition().x); | |
}, | |
get y() { | |
return px(self.body.GetPosition().y); | |
}, | |
set x(x) { | |
self.body.SetPosition(new b2Vec2(meters(x), meters(self.y))); | |
}, | |
set y(y) { | |
self.body.SetPosition(new b2Vec2(meters(self.x), meters(y))); | |
}, | |
get vx() { | |
return px(self.body.GetLinearVelocity().x); | |
}, | |
get vy() { | |
return px(self.body.GetLinearVelocity().y); | |
}, | |
set vx(x) { | |
self.body.SetLinearVelocity(new b2Vec2(meters(x), meters(self.vy))); | |
}, | |
set vy(y) { | |
self.body.SetLinearVelocity(new b2Vec2(meters(self.vx), meters(y))); | |
}, | |
apply:function(x,y){ | |
self.body.ApplyForce(new b2Vec2(meters(x),meters(y)),self.body.GetWorldCenter()); | |
} | |
}); | |
return self.init(); | |
} | |
var self = Class({ | |
world:null, | |
ptm:null, | |
init: function() { | |
return self; | |
self.world=new b2World(new b2Vec2(0, .1), false); | |
}, | |
update:function(){ | |
self.world.Step( 1000/60, 10 ); | |
self.world.DrawDebugData(); | |
self.world.ClearForces(); | |
}, | |
body:function(args) { | |
var fixDef = new b2FixtureDef(); | |
fixDef.density = 1.0; | |
fixDef.friction = 0.5; | |
fixDef.restitution = 0.2; | |
var bodyDef = new b2BodyDef(); | |
bodyDef.type = b2Body.b2_dynamicBody; | |
switch (args.shapeType) { | |
case "CIRCLE": | |
fixDef.shape = new b2CircleShape(args.radius); | |
break; | |
case "POLYGON": | |
fixDef.shape = new b2PolygonShape(); | |
fixDef.shape.SetAsBox((32).toMeters() / 2, (32).toMeters() / 2); | |
break; | |
case "BOX": | |
fixDef.shape = new b2PolygonShape(); | |
fixDef.shape.SetAsBox((args.width).toMeters() / 2, (args.height).toMeters() / 2); | |
break; | |
var body = self.world.CreateBody(bodyDef); | |
body.CreateFixture(fixDef); | |
return Body({ | |
body:body, | |
shapeType:args.shapeType, | |
physics:self, | |
}); | |
} | |
} | |
}); | |
return self.init(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment