Skip to content

Instantly share code, notes, and snippets.

@sntran
Last active August 29, 2015 14:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sntran/50053f2572356b922303 to your computer and use it in GitHub Desktop.
Save sntran/50053f2572356b922303 to your computer and use it in GitHub Desktop.
Physics System with makr.js and p2.js
function Physics(bodyConfs, shapeConfs) {
this.body = bodyConfs;
this.shape = shapeConfs;
}
function PhysicsSystem(gravity) {
makr.IteratingSystem.call(this);
this.registerComponent(ComponentRegister.get(Position));
this.registerComponent(ComponentRegister.get(Rotation));
this.registerComponent(ComponentRegister.get(Physics));
this.world = new p2.World({
gravity: gravity
});
}
inherits(PhysicsSystem, makr.IteratingSystem, {
onAdded: function(entity) {
var physics = entity.get(ComponentRegister.get(Physics));
var bodyConfs = physics.body;
var shapeConfs = physics.shape;
var body = new p2.Body(bodyConfs);
body.id = entity.id;
var shapeType = shapeConfs.type;
// shapeType is of Circle, Plane, Rectangle, Convex, etc...
var shape = new p2[shapeType](shapeConfs);
body.addShape(shape);
this.world.addBody(body);
},
process: function(entity, elapsed) {
// Move physics bodies forward in tim
this.world.step(1/60);
var position = entity.get(ComponentRegister.get(PhysicsBody));
var rotation = entity.get(ComponentRegister.get(Rotation));
var body = this.world.getBodyById(entity.id);
// Transfer positions of the physics objects to related components
position.x = body.position[0];
position.y = body.position[1];
rotation.angle = body.angle;
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment