Cocos2d-x basics

Some articles about Cocos2d-x framework

Switching between scenes

Posted at — Sep 26, 2020

The Cocos2d developers wanted the internal part of the game look like theater or movie: there is [the director(https://docs.cocos2d-x.org/api-ref/cplusplus/v4x/d7/df3/classcocos2d_1_1_director.html)] and some scenes. The director orders scenes to change one another.

Actually, the Director has following methods to change the scenes:

Anyway, the new scene completely redraws everything that was on the screen before it. In most cases this behavior is good, but there are some exceptions. Let’s say you want to put the game on pause or display some message. In order to make this delay more obvious for the player it will be better to show the new scene over some content from the old one.

For example, the switch may look like this:

First there was a scene with candle animation and rotating UFO. Then it gets changed with a new scene, but this new scene has to use older background.

There is no exact method in Cocos2d to get this effect. However you can achieve it in two steps: first keep an image from the old scene and then use it as a background on the new one.

Like that:

void StaticInterruptScene::switchToInstantScene() {
    const Size visibleSize = Director::getInstance()->getVisibleSize();
    RenderTexture* rt      = RenderTexture::create(visibleSize.width,
                                                   visibleSize.height);

    rt->begin();
    this->visit();
    rt->end();
    rt->getSprite()->setAnchorPoint(Vec2(0, 0));

    Scene* ims = InstantMenuScene::create(rt);

    Director::getInstance()->pushScene(ims);
  }
}

Here the RenderTexture instance keeps an image generated for the old scene. The InstantMenuScene is a class for a new scene; it receives stored image as a constructor parameter and uses for a background. The usage itself is quite trivial, but you can find it here.