Detecting collisions
When a collision between physics objects occurs, you want to take action against the physics bodies, for example, showing an explosion and showing a particle. In this recipe, you learn how to detect a collision in the physics world.
How to do it...
Firstly, you have to create the event listener in the
init
method as follows:auto contactListener = EventListenerPhysicsContact::create(); contactListener->onContactBegin = [](PhysicsContact& contact){ CCLOG("contact begin"); auto shapeA = contact.getShapeA(); auto bodyA = shapeA->getBody(); auto shapeB = contact.getShapeB(); auto bodyB = shapeB->getBody(); return true; }; this->getEventDispatcher()->addEventListenerWithSceneGraphPriority(contactListener, this);
Next, you have to set the contact test bit mask to the physics bodies that you want to check the collisions for. In this recipe, you set the wall body and the sprite body as follows:
auto wallBody = PhysicsBody::createEdgeBox...