Display pause menu before entering background?

I am using cocos2d-x 3.2.

Is there any way to display a “paused game” menu BEFORE entering the background? What I would like my game to do is this:

  • game is about to enter the background (either due to user manually sending the game to the background, receiving a phone call, etc), so a “pause menu” is displayed. Animation and music is stopped.
  • game enters background
  • game moves back to foreground and the user sees the “pause menu”.
  • user presses the “resume” button and animation and music resumes

I have the following code currently:

void AppDelegate::applicationDidEnterBackground() {
    //SimpleAudioEngine::sharedEngine()->pauseBackgroundMusic();

    Scene* scene = Director::getInstance()->getRunningScene();
    GameLayer* gameLayer = scene->getChildByName<GameLayer*>("GameLayer");
    if (gameLayer != 0)
    {
        gameLayer->pauseGame();
    }
    
    Director::getInstance()->stopAnimation();
}

The pauseGame() function is responsible for displaying the pause game menu. The problem I am facing is that the game enters the background before the next update loop occurs, which means the pause game menu is not actually displayed until the game enters the foreground (this only happens if I call Director::getInstance()->startAnimation() in applicaitonWillEnterForeground). If startAnimation() is never called in applicationWillEnterForeground(), then the pause game menu never displays at all. Is there any way to get around this? I would like for the callback function of pressing the “resume game” button to resume the game animation and music. Thanks for any info!

I usually put a flag like bool _isGamePaused in my gamescene, set it to true in gamescene’s pauseGame() method and check it in the gameloop.

This way the pause menu could also be animated.

So call Director::getInstance()->startAnimation() in animationWillEnterForeground()
And when the user pushes the “resume button” set _isGamePaused to true and start background music.

Sorry, set _isGamePaused to false when user pushes resume button…

Just a typo.

Thanks, that got me on the right track. With your advice I ended up using a _isPaused flag check it in the update() method. I am now doing the following to make sure that all of the animated elements on the gameLayer are paused:

Vector<Node*> children = _gameLayer->getChildren();
for (auto child : children)
{
    child->pauseSchedulerAndActions();
}

Hi…
why need to do it for every child?

I mean you can simply do _gameLayer->pause() or something like that…
It will automatically do what you’re implementing through loop.
I used this thing when I developed a game in cocos2d JS… So I think this API should be available with cocos2d-X too.

Just check…

Node::pause() is not recursive by default.
since it calls void EventDispatcher::pauseEventListenersForTarget(Node* target, bool recursive/* = false */)

1 Like