Search code examples
iosobjective-cxcodecocos2d-iphone

Game Freezes when switching scenes (Cocos2d)


When I first run my app, everything works great, but when I close it (just press the home button, not close the process) and reopen it, if I tap any button that changes the scene, it freezes. The background music still plays and Xcode doesn't tell me there were any errors, but the whole screen is frozen and the button I pressed is stuck in the highlighted state. This is the code I'm using that causes it to freeze after closed and reopened:

[[CCDirector sharedDirector] replaceScene:[PlayScene scene]
                           withTransition:[CCTransition 
transitionPushWithDirection:CCTransitionDirectionLeft duration:0.5f]];

Also, this may be caused by the same problem. When I exit the app out of the play screen, which has animation, and reopen, the animations have stopped. I figure I can fix this by pausing the game when the app is inactive.

Update: Now Xcode does give an error. When the app is closed, I get the EXC_BAD_ACCESS error on the following line in the swapBuffers method of the CCGLView.m class:

if(![_context presentRenderbuffer:GL_RENDERBUFFER])

Solution

  • Once Xcode actually gave an error, I was able to find this solution:

    - (void)applicationDidEnterBackground:(UIApplication *)application
    {
        [[CCDirector sharedDirector] pause];
        [[CCDirector sharedDirector] stopAnimation]; // Add
    }
    
    - (void)applicationWillEnterForeground:(UIApplication *)application
    {
        [[CCDirector sharedDirector] resume];
        [[CCDirector sharedDirector] startAnimation]; // Add
    }