cocos2dx之初始化layer

我们在进入layer的时候,首先如果使用默认的方法(
LAYER_CREATE_FUNC

)初始化,那么它就会进入init,这个方法你可以初始化你的layer和一些sprites,如果你想自己重写layer的onEnter/onExit的话,那么务必请注意,你要在你的onEnter/onExit里面写上基类的Base::onEnter、Base::onExit,否则的话,程序会收不到消息的。

举例子说明:

void GameController::InitController() {
    CCMenuItemImage *menuitem = CCMenuItemImage::create(
                                                                                        "NextLayeNormal.png",
                                                                                        "NextLayeSelected.png",
                                                                                        this,
                                                                                        menu_selector(GameController::CreateNextScene));
}

我初始化我的menu,回调一个:

GameController::CreateNextScene

才响应menu的点击消息。

如果我这个时候在GameController里面没有重写onEnter/onExit,那么我就它自动会接受到menu的点击消息。但是,一旦你重写了onEnter/onExit,就一定要写基类的onEnter/onExit的调用,否则,我在初始化menu的时候不会回调到GameController::CreateNextScene里面。也就是不会接受到消息。


我们看下layer的onEnter/onExit的源码:

void CCLayer::onEnter()
{
    CCDirector* pDirector = CCDirector::sharedDirector();
    // register 'parent' nodes first
    // since events are propagated in reverse order
    if (m_bIsTouchEnabled)
    {
        this->registerWithTouchDispatcher();
    }

    // then iterate over all the children
    CCNode::onEnter();

    // add this layer to concern the Accelerometer Sensor
    if (m_bIsAccelerometerEnabled)
    {
        pDirector->getAccelerometer()->setDelegate(this);
    }

    // add this layer to concern the kaypad msg
    if (m_bIsKeypadEnabled)
    {
        pDirector->getKeypadDispatcher()->addDelegate(this);
    }
}

void CCLayer::onExit()
{
    CCDirector* pDirector = CCDirector::sharedDirector();
    if( m_bIsTouchEnabled )
    {
        pDirector->getTouchDispatcher()->removeDelegate(this);
        unregisterScriptTouchHandler();
    }

    // remove this layer from the delegates who concern Accelerometer Sensor
    if (m_bIsAccelerometerEnabled)
    {
        pDirector->getAccelerometer()->setDelegate(NULL);
    }

    // remove this layer from the delegates who concern the kaypad msg
    if (m_bIsKeypadEnabled)
    {
        pDirector->getKeypadDispatcher()->removeDelegate(this);
    }

    CCNode::onExit();
}

看了源码就知道了,如果不调用的基类的onEnter/onExit那么我无法得到消息代理。也就不能接收到消息

你可能感兴趣的:(cocos2dx之初始化layer)