Skip to content

Instantly share code, notes, and snippets.

@wellcaffeinated
Created December 6, 2013 21:05
Show Gist options
  • Save wellcaffeinated/7832084 to your computer and use it in GitHub Desktop.
Save wellcaffeinated/7832084 to your computer and use it in GitHub Desktop.
PhysicsJS collision monitoring strategies
// If you want to subscribe to collision pairs
// emit an event for each collision pair
world.subscribe('collisions:detected', function( data ){
var c;
for (var i = 0, l = data.collisions.length; i < l; i++){
c = data.collisions[ i ];
world.publish({
topic: 'collision-pair',
bodyA: c.bodyA,
bodyB: c.bodyB
});
}
});
// subscribe to collision pair
world.subscribe('collision-pair', function( data ){
// data.bodyA; data.bodyB...
});
// If extending a body and you want to handle its collision
world.subscribe('collisions:detected', function( data ){
var c;
for (var i = 0, l = data.collisions.length; i < l; i++){
c = data.collisions[ i ];
if ( c.bodyA.collide ){
c.bodyA.collide( c.bodyB );
}
if ( c.bodyB.collide ){
c.bodyB.collide( c.bodyA );
}
}
});
// mixin to the base body class. Adds a method to all bodies.
Physics.body.mixin('collide', function( other ){
if ( other ){
// do some default action
}
return true;
});
// bodies have an (overridable) collide function
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment