cocos2dx源码分析:场景切换

cocos2dx的Director管理场景切换,其中有几个和场景相关的成员变量

 /* The running scene */
Scene *_runningScene;/*当前正在运行的场景,即渲染中的场景*/
/* will be the next 'runningScene' in the next frame
nextScene is a weak reference. */
Scene *_nextScene;/*下一帧_nextScene会替换_runningScene*/
/* scheduled scenes */
Vector<Scene*> _scenesStack;/*场景栈*/

程序启动后,使用Director::runWithScene进入第一个Scene,它把scene存储场景栈中,并设置_nextScene,设置_nextScene后,下一帧就可成为_runningScene

void Director::runWithScene(Scene *scene) { CCASSERT(scene != nullptr, "This command can only be used to start the Director. There is already a scene present.");
    CCASSERT(_runningScene == nullptr, "_runningScene should be null");

    pushScene(scene);
    startAnimation();
}
void Director::pushScene(Scene *scene)
{
    CCASSERT(scene, "the scene should not null");

    _sendCleanupToScene = false;

#if CC_ENABLE_GC_FOR_NATIVE_OBJECTS
    auto sEngine = ScriptEngineManager::getInstance()->getScriptEngine();
    if (sEngine)
    {
        sEngine->retainScriptObject(this, scene);
    }
#endif // CC_ENABLE_GC_FOR_NATIVE_OBJECTS
    _scenesStack.pushBack(scene);
    _nextScene = scene;
}

之后如果想再添加新场景有两种方法,
1. 使用pushScene覆盖在当前场景之上,此时当前场景并未被销毁,当覆盖在其之上的场景销毁时,此场景可以继续运行;
2. 使用replaceScene替换当前场景,当前场景数据在下一帧会被销毁,无法恢复。

void Director::replaceScene(Scene *scene)
{
    //CCASSERT(_runningScene, "Use runWithScene: instead to start the director");
    CCASSERT(scene != nullptr, "the scene should not be null");

    if (_runningScene == nullptr) {
        runWithScene(scene);
        return;
    }

    if (scene == _nextScene)
        return;

    if (_nextScene)
    {
        if (_nextScene->isRunning())
        {
            _nextScene->onExit();
        }
        _nextScene->cleanup();
        _nextScene = nullptr;
    }

    ssize_t index = _scenesStack.size() - 1;

    _sendCleanupToScene = true;
#if CC_ENABLE_GC_FOR_NATIVE_OBJECTS
    auto sEngine = ScriptEngineManager::getInstance()->getScriptEngine();
    if (sEngine)
    {
        sEngine->retainScriptObject(this, scene);
        sEngine->releaseScriptObject(this, _scenesStack.at(index));
    }
#endif // CC_ENABLE_GC_FOR_NATIVE_OBJECTS
    /*直接替换了栈上的当前场景,当前场景在下一帧会被销毁*/
    _scenesStack.replace(index, scene);

    _nextScene = scene;
}

你可能感兴趣的:(cocos2d-x)