Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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