我正在研究我的Cocos2d-x cpp项目。我已成功添加触摸事件以在Layer中移动背景。现在我想将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);
答案 0 :(得分:1)
不要将CCMenuItem直接添加到图层。将它们添加到CCMenu并将CCMenu添加到您的图层。
答案 1 :(得分: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一样。