EventListenerPhysicsContact Not Working as Expected

Could someone help me, I am trying to use EventListenerPhysicsContact::create() as in many tutorial and code snippets but my onBeginContact(PhysiscContact &contact) method is not getting triggered.

The physics collision is happening but event is not triggering collision check. Am I missing something or is there a bug in the event listener? I have also following the Test CPP PhysicsContactTest sample to make sure my code is setup correctly.

I created my physic shapes using PhysicsEditor and do not have any issue loading the shapes and seeing they are colliding and bouncing off each other after collision.


My Code CCTestingScene.cpp (4.3 KB)

There are 4 methods that are called in the init() method:

void initObjectsWithPhysics(); //creates scene and adds boundary to screen
*** void initPhysicsContact(); //creates the physics contact event listener
void initCatcher(); //creates a box and adds physics body
void initBox(); // creates the 2nd box that collides with 1st box 

Code that adds Physics Contact Event Listener

void CCTestingScene::initPhysicsContact()
{
    //physics listener
    auto contactListener = EventListenerPhysicsContact::create();
    contactListener->onContactBegin = CC_CALLBACK_1(CCTestingScene::onContactBegin, this);
    this->getEventDispatcher()->addEventListenerWithSceneGraphPriority(contactListener, this);

    this->listener = contactListener; //internal pointer to listener to remove in Destructor
    CCLOG("initPhysicsContact()...");
}

bool CCTestingScene::onContactBegin(const PhysicsContact &contact)
{
    CCLOG("Collision detected!");
    return true;
}

There is no such example sample.

You forgot to set the contact test bitmask on your objects:

/*
NOTICE: If you don’t set the contact test bitmask on your physics
body, the event listener’s onContactBegin callback will not
be called. */

You have to set it to every physics body you want the callback handler to be called upon.
E.g. boundaryBody->setContactTestBitmask(0xFFFFFFFF); Every contact with the boundaryBody will now be reported through the callback.

Read about it here:
http://cocos2d-x.org/programmersguide/12/

Thanks @iQD. I figured the issue that was preventing the onBeginContact method from getting called when collision was happening.

I was adding all my sprites to the scene, rather than this->addChild(sprite); that is why the event listener for some reason was not getting triggered. I had also assigned the listener to the scene as well. Maybe scene cannot trigger event listener, who knows, I have not looked into the API reference.

BTW, if you look into the sample test code inside the cocos2d library, there is sample class called PhysicsContactTest.h and .cpp, unless you have deleted the sample code, it should be there.