Book Image

Cocos2d-x Cookbook

By : Akihiro Matsuura
Book Image

Cocos2d-x Cookbook

By: Akihiro Matsuura

Overview of this book

Table of Contents (18 chapters)
Cocos2d-x Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

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...

  1. 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);
  2. 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...