0

我正在开发我的 Cocos2d-x cpp 项目。我已成功添加触摸事件以在图层中移动背景。现在想把CCMenuItemLabel加到Layer上,但是我发现CCMenuItemLabel在我触摸的时候不起作用。我该如何解决?

我在我的图层中添加了这些功能:

virtual void ccTouchesBegan (CCSet *pTouches, CCEvent *pEvent);
virtual void ccTouchesMoved (CCSet *pTouches, CCEvent *pEvent);
virtual void ccTouchesEnded (CCSet *pTouches, CCEvent *pEvent);

在 MyLayer::init() 函数中:

this->setTouchEnabled(true);

CCLabelTTF* test = CCLabelTTF::create("tesetdd","Arial",40);
CCMenuItemLabel* menuLabel = CCMenuItemLabel::create(test,this,menu_selector(GameWall::menuCall));
menuLabel->setPosition(ccp(winSize.width/2,winSize.height/2));
this->addChild(menuLabel,1);

更新:我已将 CCMenuItemLabel 放入 CCMenu。但它仍然不起作用。

CCLabelTTF* test = CCLabelTTF::create("tesetdd","Arial",40);
CCMenuItemLabel* menuLabel = CCMenuItemLabel::create(test,this,menu_selector(GameWall::menuCall));
menuLabel->setPosition(ccp(winSize.width/2,winSize.height/2));
CCMenu* menu = CCMenu::create(menuLabel,NULL);
menu->setPosition(CCPointZero);
this->addChild(menu,1);
4

2 回答 2

1

不要将 CCMenuItems 直接添加到图层。将它们添加到 CCMenu 并将该 CCMenu 添加到您的图层。

于 2013-11-13T09:24:38.723 回答
0

首先,感谢@Kreiri。

我已将触摸事件功能更改为

virtual bool ccTouchBegan (CCTouch *pTouch, CCEvent *pEvent);
virtual void ccTouchMoved (CCTouch *pTouch, CCEvent *pEvent);
virtual void ccTouchEnded (CCTouch *pTouch, CCEvent *pEvent);

我又添加了两个功能

virtual void onEnter();
virtual void registerWithTouchDispatcher();  

我将初始代码移至 onEnter

CCLabelTTF* test = CCLabelTTF::create("tesetdd","Arial",40);
CCMenuItemLabel* menuLabel =          CCMenuItemLabel::create(test,this,menu_selector(GameWall::menuCall));
menuLabel->setPosition(ccp(winSize.width/2,winSize.height/2));
CCMenu* menu = CCMenu::create(menuLabel,NULL);
menu->setPosition(CCPointZero);
this->addChild(menu,1);

向 onEnter() 添加另外三个代码:

this->setTouchEnabled(true);
registerWithTouchDispatcher();
menu->registerWithTouchDispatcher();

而 registerWithTouchDispatcher() :

void GameWall::registerWithTouchDispatcher(){
    //registe the single point touch,and take over all touch event
    CCDirector::sharedDirector()->getTouchDispatcher()->addTargetedDelegate(this,kCCMenuHandlerPriority,true);
}

最后,不要忘记在 onExit() 中 romoveDelegate():

void GameWall::onExit(){
    CCDirector::sharedDirector()->getTouchDispatcher()->removeDelegate(this);
}

让我解释一下,检查文件 registerWithTouchDispatcher() 说If isTouchEnabled, this method is called onEnter.Override it to change the way CCLayer receives touch events.CCMenu 一样。

于 2013-11-13T11:01:23.180 回答