Search code examples
c++cocos2d-x

CCMenuItemLabel doesn't work when isTouchEnabled is true?


I am working on my Cocos2d-x cpp project. I have successfully add touch event to move the background in Layer. Now I want to add CCMenuItemLabel to the Layer, but I find that CCMenuItemLabel doesn't work when I Touch it. How can I solve it?

I have add these functions in my Layer:

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

In MyLayer::init() function:

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

Update:I have put CCMenuItemLabel into the CCMenu. But it still doesn't work.

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

Solution

  • First, thanks for @Kreiri.

    I have change my Touch Event function to

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

    and I add two more functions

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

    and I move initial code to 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);
    

    add three more code to onEnter():

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

    While registerWithTouchDispatcher() :

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

    Finally, don't forget to romoveDelegate() in onExit():

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

    Let me explain, check the document registerWithTouchDispatcher() says If isTouchEnabled, this method is called onEnter. and Override it to change the way CCLayer receives touch events. And same with CCMenu.