makzan/github-as-tutorial — pull request #1 by makzan (2014-07-07 06:25:30+00:00)
Title: Step 3 – Collision detection

In this step, we add collision detection to the ball and the hoop. By adding the detection sensor, we can know if a ball passes through the hoop and we give player scores.

This is the essential code we need:

``` javascript
physics.setupContactListener = function() {
// contact
var contactListener = new Box2D.Dynamics.b2ContactListener;
contactListener.BeginContact = function(contact, manifold) {
if (contact.GetFixtureA().IsSensor() || contact.GetFixtureB().IsSensor()) {
game.increaseScore();
}

// world boundary.
var userDataA = contact.GetFixtureA().GetBody().GetUserData();
var userDataB = contact.GetFixtureB().GetBody().GetUserData();
if (userDataA !== null && userDataA.isBoundary ||
userDataB !== null && userDataB.isBoundary) {

// which one is boundary?
var boundary = contact.GetFixtureA().GetBody();
var body = contact.GetFixtureB().GetBody();

if (userDataB !== null && userDataB.isBoundary) {
boundary = contact.GetFixtureB().GetBody();
body = contact.GetFixtureA().GetBody();
}

physics.bodiesToBeRemove.push(body);

}
};
this.world.SetContactListener(contactListener);
};
```