Game Development Reference
In-Depth Information
void ContactListener::BeginContact(b2Contact* contact)
{
b2Body* bodyA = contact- > GetFixtureA()- > GetBody();
b2Body* bodyB = contact- > GetFixtureB()- > GetBody();
BodySprite* bodySpriteA = (BodySprite*)bodyA- > GetUserData();
BodySprite* bodySpriteB = (BodySprite*)bodyB- > GetUserData();
if ([bodySpriteA isKindOfClass:[Plunger class]] &&←
[bodySpriteB isKindOfClass:[Ball class]])
{
Plunger* plunger = (Plunger*)bodySpriteA;
// . . . perform custom code for collision handling
}
else if ([bodySpriteB isKindOfClass:[Plunger class]] &&←
[bodySpriteA isKindOfClass:[Ball class]])
{
Plunger* plunger = (Plunger*)bodySpriteB;
// . . . perform custom code for collision handling
}
}
The previous approach also requires you to import the header files for each colliding
BodySprite class. Over time, the collision-handling class knows about most game
objects and can become quite complex and hard to read. Instead, you want to have each
BodySprite class handle the collision events that it's involved in. This keeps the
code cleanly separated and easier to maintain and turns the job of the collision handling
class to one of delegating the collision events to the colliding objects.
The ContactListener class ( Listing 13-18 ) in the PhysicsBox2DPinball01 project
defines two additional methods next to the regular Box2D collision callback methods
to perform the delegation of collision events.
Listing 13-18 . The ContactListener Class Definition
class ContactListener : public b2ContactListener
{
private:
void BeginContact(b2Contact* contact);
 
 
Search Nedrilad ::




Custom Search