Stop animation when game is paused and then resume in cocos2d

Based on the research I did online, I came up with this code to pause and resume the game:

-(void)pauseGame:(UIApplication *)application{
[[CCDirector sharedDirector] pause];
//do other actions necessary}

-(void)resumeGame:(UIApplication *)application{
[[CCDirector sharedDirector] resume];
//do other actions}

      

This works great, but my problem is the game is paused, closed and reopened. Usually, if you pause the game and then close it when you open it, everything should be paused. And after some research I ended up with this code in the Appdelegate:

-(void) applicationDidEnterBackground:(UIApplication*)application{
if( [navController_ visibleViewController] == director_ )
    [director_ stopAnimation];

RandomScene *s = [RandomScene node];
if(s.layer.gameStatus == FALSE)
{
    [[CCDirector sharedDirector]pause];
    [[CCDirector sharedDirector]stopAnimation];
    [s.layer stopAllActions];
}}

      

With this code, when I open the game again, the timer still pauses along with all touch events. However, my animation is still running, so my sprites still move when they shouldn't. How can I stop the animation completely when the game is open again?

+3


source to share


2 answers


After further research, I was able to find a solution to the problem I encountered through this post . I removed the pause of CCDirector and resumed in my pauseGame and resumeGame routines, then added the following:

//pause
[sprite.actionManager pauseTarget:sprite];

//resume
[sprite.actionManager resumeTarget:sprite];

      

This stopped the animation and kept the "paused" state even if the game was closed and then reopened and I didn't even need to play with the AppDelegate class :). Hope this helps others too.



UPDATE: just in case someone creates the sprite using a loop, this is how I managed to create a pause and resume function for it:

[sprite.actionManager pauseAllRunningActions];
[sprite.actionManager resumeTargets:[NSSet setWithArray:spriteArray]];

      

please note the difference between the two (resumeTarget and resumeTargets), after which resuming the request will ask for the NSSet, I just passed the array objects to the NSSet with the above code.

+2


source


For this, I suggest you manually manage your sprites. Make a way in the main game scene that will stop your game. You can pause sprites and animations using a method pauseSchedulersAndActions

on your sprite objects. And resume these steps in resumeMethod in your GameScene.



Call this method from AppDelegate with a reference to runScene using CCDirector.

+2


source







All Articles