Search code examples
c++cocos2d-x

How can I get other layer in the same scene in cocos2d-x?


I have several layers in the scene, like TLayer,HLayer,TouchLayer. How can I get HLayer in HLayer? The solution I take is that I pass Layer to other Layer. However I met some problems recently. I push the Scene and pop Scene while TouchLayer still exists. So my problem is that is it right to pass HLayer to TouchLayer. Or is there a better way to do it in Cocos2d-x?

In the init() function in Scene:

this->setbackgroundLayer(BackgroundLayer::create());
CC_BREAK_IF(!backgroundLayer);
this->addChild(backgroundLayer);

this->setTLayer(TcharacterLayer::create(backgroundLayer->tianzige));
CC_BREAK_IF(!TLayer);
this->addChild(TLayer);

this->setHLayer(HcharacterLayer::create(testCharacter,backgroundLayer->tianzige_draw));
CC_BREAK_IF(!HLayer);
this->addChild(HLayer);

this->settouchLayer(TouchLayer::create(TLayer,HLayer));
CC_BREAK_IF(!touchLayer);
this->addChild(touchLayer);

I made my own create function:

TouchLayer* TouchLayer::create(TcharacterLayer* t,HcharacterLayer* h){
    TouchLayer* pRet = new TouchLayer();
    if (pRet && pRet->init(t,h))
    {
        pRet->autorelease();
        return pRet;
    }else
    {
        delete pRet;
        pRet = NULL;
        return NULL;
    }
}

Solution

  • Here's how we've done this in the past. Define a set of tags for our layers.

    typedef enum {
        kBgLayerTag,
        kHLayerTag,
        kTLayerTag,
        kTouchLayerTag
        } MyLayerTags
    

    Then while creating the layers set layer specific tags:

    this->setTLayer(TcharacterLayer::create(backgroundLayer->tianzige));
    CC_BREAK_IF(!TLayer);
    TLayer->setTag(kTLayerTag);
    this->addChild(TLayer);
    

    And in TouchLayer access the TLayer and others like:

    TcharacterLayer* myTLayer = this->getParent()->getChildByTag(kTLayerTag);