CCMenuItemLabel 在 isTouchEnabled 为 true 时不起作用?

CCMenuItemLabel doesn't work when isTouchEnabled is true?

本文关键字:不起作用 true isTouchEnabled CCMenuItemLabel      更新时间:2023-10-16

我正在做我的Cocos2d-x cpp项目。我已经成功添加触摸事件以移动图层中的背景。现在我想将 CCMenuItemLabel 添加到图层,但我发现 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);

更新:I已将 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);

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

首先,感谢您的@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();  

我将初始代码移动到输入

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 相同。