2014-08-29 38 views
0

我试图实现一种简单的方法来在我的类中启用和禁用Touch监听器。我试着写我的类中的方法:在Cocos 2D-X中添加和删除事件监听器3.2

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); 
    } 

} 

我希望能够再调用setTouchEnabled(true)setTouchEnabled(false)从这个类中的任何其他方法中。但是,由于_touchListener在函数结束时被释放,所以这不起作用。当我试图在我的头文件中声明EventListener *_touchListener,我在XCode中收到错误在这条线:

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

错误说,没有成员名为onTouchesBegan存在cocos2d::EventListener

我假设必须有一个简单的方法来做到这一点。

+0

看看这个:http://www.cocos2d-x.org/wiki/How_To_Subclass_Sprite_And_Add_Event_Listeners。我想你会因为某些类的重命名而在3.2版本中遇到一些编译错误,但这些很容易修复。 – GameDeveloper 2014-08-29 15:38:33

回答

1

你需要学习C++第一:)

在你的头文件中定义_touchListener首先,作为HelloWorld成员。然后修改你的CPP文件:

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; 
    } 

} 
+0

感谢您的帮助,我得到了它的工作! – Kevin 2014-08-29 21:04:16