Game Development Reference
In-Depth Information
Creating a contact listener
Besides collision filters, one other feature in Box2D that helps with collision management
is the creation of a contact listener.
Inside the
initPhysics
method, we create the
world
object like this:
b2Vec2 gravity;
gravity.Set(0.0f, 0.0f);
_world = new b2World(gravity);
_world->SetAllowSleeping(true);
_world->SetContinuousPhysics(true);
_collisionListener = new CollisionListener();
_world->SetContactListener(_collisionListener);
Our
CollisionListener
class extends the Box2D
b2ContactListener
class, and
it must implement at least one of the following methods:
•
void BeginContact(b2Contact* contact);
•
void EndContact(b2Contact* contact);
•
void PreSolve(b2Contact* contact, const b2Manifold*
oldManifold);
•
void PostSolve(b2Contact* contact, const b2ContactIm-
pulse* impulse);
These events are all related to a contact (collision) and are fired at different stages of a con-
tact.
Note
Sensor objects can only ever fire the
BeginContact
and
EndContact
events.
In our game, we implement two of these methods. The first is:
void CollisionListener::BeginContact(b2Contact* contact) {
b2Body * bodyA = contact->GetFixtureA()->GetBody();
b2Body * bodyB = contact->GetFixtureB()->GetBody();