Skip to content
This repository has been archived by the owner on Dec 15, 2019. It is now read-only.

Collisions

Jasper edited this page Apr 22, 2014 · 3 revisions

Collision detection is a combination of three behaviors: sweep-prune, body-collision-detection, and body-impulse-response.

  • sweep-prune is a broadphase helper to speed up collision detection process
  • body-collision-detection is a narrowphase helper to accurately detect collisions and collision information. It can be used on its own if desired... but that would be a strange use-case.
  • body-impulse-response is a behavior that responds to events emitted by body-collision-detection and applies impulses to give bodies a collision effect.

Collision Monitoring Strategies

Strategy 1 - Subscribe to collision pairs

// If you want to subscribe to collision pairs
// emit an event for each collision pair
world.on('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.on('collision-pair', function( data ){
    // data.bodyA; data.bodyB...
});

Strategy 2 - Custom collision handler on a per-body basis

// If extending a body and you want to handle its collision
world.on('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

Strategy 3 - using a Query to find a specific collision

// query to find a collision between a body with label "bullet" and a body with label "box"
var query = Physics.query({
    $or: [
        { bodyA: { label: 'bullet' }, bodyB: { label: 'box' } }
        ,{ bodyB: { label: 'bullet' }, bodyA: { label: 'box' } }
    ]
});

// monitor collisions
world.on('collisions:detected', function( data, e ){
    // find the first collision that matches the query
    var found = Physics.util.find( data.collisions, query );
    if ( found ){
        // handle the collision
    }
});