Kevin
Kevin

Reputation: 3

Adding and Removing Event Listeners in Cocos 2D-X 3.2

I'm trying to implement an easy way to enable and disable a Touch listener within my class. I tried writing a method within my class:

void HelloWorld::setTouchEnabled(bool enabled)
{
    if (enabled)
    {
        auto _touchListener = EventListenerTouchAllAtOnce::create();
        _touchListener->onTouchesBegan = CC_CALLBACK_2(HelloWorld::onTouchesBegan, this);
        _eventDispatcher->addEventListenerWithSceneGraphPriority(_touchListener, this);

    }
    else if (!enabled)
    {
        _eventDispatcher->removeEventListener(_touchListener);
    }

}

I was hoping to be able to then call setTouchEnabled(true) or setTouchEnabled(false) from within any other methods in this class. However, this does not work since _touchListener is released at the end of the function. When I tried to declare EventListener *_touchListener in my header file, I received an error in XCode on this line:

_touchListener->onTouchesBegan = CC_CALLBACK_2(HelloWorld::onTouchesBegan, this);

The error said that no member named onTouchesBegan exists in cocos2d::EventListener.

I'm assuming there must be an easy way to do this.

Upvotes: 0

Views: 2959

Answers (1)

Chen
Chen

Reputation: 1672

You need to learn C++ first:)

Define _touchListener in your header file first, as a member of HelloWorld. Then modify your cpp file:

void HelloWorld::setTouchEnabled(bool enabled)
{
    if (enabled)
    {
        _touchListener = EventListenerTouchAllAtOnce::create();
        _touchListener->retain();
        _touchListener->onTouchesBegan = CC_CALLBACK_2(HelloWorld::onTouchesBegan, this);
        _eventDispatcher->addEventListenerWithSceneGraphPriority(_touchListener, this);

    }
    else if (!enabled)
    {
        _eventDispatcher->removeEventListener(_touchListener);
        _touchListener->release();
        _touchListener = nullptr;
    }

}

Upvotes: 2

Related Questions