Resume game cocos2d - ios

I used he code below to handle pause and resume buttons in my game
To Pause:
-(void)pauseTapped{
...
[[SimpleAudioEngine sharedEngine] pauseBackgroundMusic];
[[CCDirector sharedDirector] pause];
...
}
To Resume:
-(void)resumeGame: (id)sender {
...
[self removeChild:pauseMenu cleanup:YES];
[[SimpleAudioEngine sharedEngine] resumeBackgroundMusic];
[[CCDirector sharedDirector] resume];
...
}
The problem is if the used click pause then enterBackground (click Home button) mode
when he returns, the game automatically resume and the pause menu still exist
Any idea will be great
UPDATE:
the AppDelegate code:
- (void)applicationWillResignActive:(UIApplication *)application {
[[CCDirector sharedDirector] pause];
}
- (void)applicationDidBecomeActive:(UIApplication *)application {
[[CCDirector sharedDirector] resume];
}
- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application {
[[CCDirector sharedDirector] purgeCachedData];
}
-(void) applicationDidEnterBackground:(UIApplication*)application {
[[CCDirector sharedDirector] stopAnimation];
}
-(void) applicationWillEnterForeground:(UIApplication*)application {
[[CCDirector sharedDirector] startAnimation];
}
- (void)applicationWillTerminate:(UIApplication *)application {
CCDirector *director = [CCDirector sharedDirector];
[[director openGLView] removeFromSuperview];
[viewController release];
[window release];
[director end];
}
- (void)applicationSignificantTimeChange:(UIApplication *)application {
[[CCDirector sharedDirector] setNextDeltaTimeZero:YES];
}
- (void)dealloc {
[[CCDirector sharedDirector] end];
[window release];
[super dealloc];
}
Thank you

You should add a property to your app delegate that will keep track if pause was caused by user tapping pause button or automatically.
Inside YourAppDelegate.h:
#property (nonatomic) BOOL userPaused;
And inside YourAppDelegate.h:
#synthesize userPaused;
Then inside your scene's pause method, add:
YourAppDelegate *appDelegate = (YourAppDelegate *)[[UIApplication sharedApplication] delegate];
appDelegate.userPaused = YES;
And inside your scene's resume method, add:
YourAppDelegate *appDelegate = (YourAppDelegate *)[[UIApplication sharedApplication] delegate];
appDelegate.userPaused = NO;
Now you can edit your app delegate's -applicationWillResignActive: method to only resume if userPaused is not set to YES.
- (void)applicationDidBecomeActive:(UIApplication *)application {
if (!self.userPaused) {
[[CCDirector sharedDirector] resume];
}
}

Related

Push a ViewController from a Cocos2d scene

I am loading a cocos2d game inside an Storyboard. I implemented a CocosViewController that loads the cocos2d scene (IntroLayer) and IntroLayer that starts the game. I would like to go back to CocosViewController or open a new viewcontroller when the timer (countdown) is zero in the game.
I tried calling [[CCDirector sharedDirector] popScene]; when the countdown arrives to zero and with CocosViewController *cocos = [[CocosViewController alloc] init]; [cocos.navigationController dismissViewControllerAnimated:YES completion:nil];
in onExit method but the app crashes when the countdown arrives to zero, any suggestion?
My CocosViewController set up cocos2d
-(void)setupCocos2d {
CCDirector *director = [CCDirector sharedDirector];
//[[[self navigationController] navigationBar] setHidden:YES];
if([director isViewLoaded] == NO)
{
// Create the OpenGL view that Cocos2D will render to.
CCGLView *glView = [CCGLView viewWithFrame:self.view.bounds
pixelFormat:kEAGLColorFormatRGB565
depthFormat:0
preserveBackbuffer:NO
sharegroup:nil
multiSampling:NO
numberOfSamples:0];
// Assign the view to the director.
director.view = glView;
// Initialize other director settings.
[director setAnimationInterval:1.0f/60.0f];
[director enableRetinaDisplay:YES];
}
// Set the view controller as the director's delegate, so we can respond to certain events.
director.delegate = self;
// Add the director as a child view controller of this view controller.
[self addChildViewController:director];
// Add the director's OpenGL view as a subview so we can see it.
[self.view addSubview:director.view];
[self.view sendSubviewToBack:director.view];
// Finish up our view controller containment responsibilities.
[director didMoveToParentViewController:self];
// Run whatever scene we'd like to run here.
NSArray *parameters = [[NSArray alloc] initWithObjects:#"3", #"sound", #"countdown", nil];
if(director.runningScene)
[director replaceScene:[IntroLayer scene];
else
[director pushScene:[IntroLayer scene];
}
- (void)viewDidLoad
{
[super viewDidLoad];
NSLog(#"cocos2d controller viewdidload");
[self setupCocos2d];
}
-(void)viewDidUnload {
NSLog(#"did unload");
[[CCDirector sharedDirector] setDelegate:nil];
[[CCDirector sharedDirector] end];
}
IntroLayer creates the scene for the game. This is my onExit method:
-(void) onExit{
NSLog(#"Introscene exit");
[super onExit];
}
And this is the game. I want to load a viewcontroller when the game finished.
-(void)update:(ccTime)dt{
if (myTime > 0) {
myTime -= (float)dt;
[timeLabel setString:[NSString stringWithFormat:#"%.2f", myTime]];
} else {
myTime = 0;
[timeLabel setString:[NSString stringWithFormat:#"0.00"]];
[[CCDirector sharedDirector] popScene];
}
if (clicks < currentClicks) {
clicks = currentClicks;
//[clicksLabel setString:[NSString stringWithFormat:#"%i", clicks]];
}
}
-(void) onExit
{
[super onExit];
[[CCDirector sharedDirector] stopAnimation];
CocosViewController *cocos = [[CocosViewController alloc] init];
[cocos.navigationController dismissViewControllerAnimated:YES completion:nil];
// [cocos.navigationController popViewControllerAnimated:YES];
//AppDelegate *app = (AppDelegate *)[[UIApplication sharedApplication] delegate];
//[app.navController popViewControllerAnimated:YES];
//dismissModalViewControllerAnimated:YES
NSLog(#"game exit");
}
For pop IntroLayer To ViewConrtroller As below code
[[[CCDirector sharedDirector] navigationController] popViewControllerAnimated:YES];

CCButton not working completely when pressed in Cocos2D v3 iOS

I have a gameplay scene, over which I add a CCNode as a child. My Game Over node has a replay CCButton in it.
The button is supposed to restart the game play scene. The problem is, when I press the "Restart" button, it goes through the lines but it doesn't perfrom replaceScene. Also it doesn't highlight when pressed. Here's my relevant code:
The code where I add the Game Over Node in my GamePlay Class (.m):
CCNode GameOver = [[GameOverNode alloc] init];
[self unscheduleAllSelectors];
[self stopAllActions];
[[OALSimpleAudio sharedInstance] stopBg];
[[CCDirector sharedDirector] stopAnimation];
[[CCDirector sharedDirector] pause];
[self addChild:GameOver z:5];
and here's the code for GameOver Class (.h):
#interface GameOverNode:CCNode {
CCButton *_aButton;
}
#property (nonatomic, retain) CCButton *aButton;
- (id)init;
- (void)ButtonPressed:(id)sender;
and Game Over (.m):
-(id)init {
if ( self = [super init] ){
CCSpriteFrame *replayFrame = [CCSpriteFrame frameWithImageNamed:#"Replay.png"];
_aButton = [CCButton buttonWithTitle:#"" spriteFrame:replayFrame];
_aButton.position = ccp(200,200);
[_aButton setTarget:self selector:#selector(ButtonPressed:)];
[self addChild:_aButton z:2];
}
return self;
}
- (void)ButtonPressed:(id)sender
{
NSLog(#"Button pressed");
CCTransition* t = [CCTransition transitionFadeWithDuration:0.4f];
t.outgoingSceneAnimated = YES;
t.incomingSceneAnimated = YES;
[[CCDirector sharedDirector] replaceScene:[GamePlayScene scene] withTransition:t];
}
The thing is, it prints out "Button pressed", also goes through the rest of the code of the method, but nothing happens.
I'll appreciate if you can let me know what I am doing wrong.
Thanks!
It does not work because you have paused the CCDirector. Remove the following line:
[[CCDirector sharedDirector] pause];
Alternatively if you really need that, resume the director before you attempt to replace the scene.
[[CCDirector sharedDirector] resume];
[[CCDirector sharedDirector] replaceScene:[GamePlayScene scene] withTransition:t];

How to stop cocos2d accumulating animation delta

I have a weird situation where if my app goes to the background and comes back to the foreground the animations are accumulated somehow and applied super fast. e.g. a CCRotateBy catches up for the time the app was in the background and spins the sprites really fast.
My app delegate has the correct application state handling I think..
- (void)applicationWillResignActive:(UIApplication *)application {
[[CCDirector sharedDirector] pause];
}
- (void)applicationDidBecomeActive:(UIApplication *)application {
[[CCDirector sharedDirector] resume];
[[OALAudioSession sharedInstance] forceEndInterruption];
}
- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application {
[[CCDirector sharedDirector] purgeCachedData];
}
-(void) applicationDidEnterBackground:(UIApplication*)application {
[[CCDirector sharedDirector] stopAnimation];
}
-(void) applicationWillEnterForeground:(UIApplication*)application {
[[CCDirector sharedDirector] startAnimation];
[[OALAudioSession sharedInstance] forceEndInterruption];
}
- (void)applicationWillTerminate:(UIApplication *)application {
CCDirector *director = [CCDirector sharedDirector];
[[director view] removeFromSuperview];
[director end];
}
- (void)applicationSignificantTimeChange:(UIApplication *)application {
[[CCDirector sharedDirector] setNextDeltaTimeZero:YES];
}
What is causing this to happen?
Its one of the problem we face with cocos2d 2.0.
TEMP_FIX: I used manual pause for animation.
-(void) applicationWillResignActive:(UIApplication *)application
{
[[NSNotificationCenter defaultCenter] postNotificationName:#"AppEnterBackground" object:nil];
if( [navController_ visibleViewController] == director_ )
[director_ pause];
}
//In game layer
-(void)onEnter
{
[super onEnter];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(AppEnterBackground:) name:#"AppEnterBackground" object:nil];
}
-(void)onExit
{
[[NSNotificationCenter defaultCenter] removeObserver:self name:#"AppEnterBackground" object:nil];
[super onExit];
}
-(void)AppEnterBackground:(NSNotification*)notif
{
[self pauseSchedulerAndActions];
[mHero pauseSchedulerAndActions];
for(MyCoin *coin in mCoinArr)
{
[coin pauseSchedulerAndActions];
}
}
Similar way you can resume.

Black screen on iPad retina display

I've a problem with a little game application running on iPad. When I lunch the simulator iOS 5.1 with iPad retina display, the application start with my default image #x2 and after show the image go to a black screen. In normal iPad iOS 5.1 simulator run well. Xcode tell me only this:
2012-04-25 14:24:26.978 AppName[83696:10a03] cocos2d: Frame interval: 1
2012-04-25 14:24:26.980 AppName[83696:10a03] cocos2d: surface size: 1536x2048
Any idea?
Thank you
#Smamim Hossain: Same error I put my full Appdelegate.m
#import "cocos2d.h"
#import "AppDelegate.h"
#import "GameConfig.h"
#import "Intro.h"
#import "RootViewController.h"
#implementation AppDelegate
#synthesize window;
- (void) removeStartupFlicker
{
//#if GAME_AUTOROTATION == kGameAutorotationUIViewController
//#endif // GAME_AUTOROTATION == kGameAutorotationUIViewController
}
- (void) applicationDidFinishLaunching:(UIApplication*)application
[director setProjection:kCCDirectorProjection2D]
{
// Init the window
window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
if( ! [CCDirector setDirectorType:kCCDirectorTypeDisplayLink] )
[CCDirector setDirectorType:kCCDirectorTypeDefault];
[director setProjection:kCCDirectorProjection2D]
CCDirector *director = [CCDirector sharedDirector];
// Init the View Controller
viewController = [[RootViewController alloc] initWithNibName:nil bundle:nil];
viewController.wantsFullScreenLayout = YES;
//
// Create the EAGLView manually
// 1. Create a RGB565 format. Alternative: RGBA8
// 2. depth format of 0 bit. Use 16 or 24 bit for 3d effects, like CCPageTurnTransition
//
//
EAGLView *glView = [EAGLView viewWithFrame:[window bounds]
pixelFormat:kEAGLColorFormatRGB565 // kEAGLColorFormatRGBA8
depthFormat:0 // GL_DEPTH_COMPONENT16_OES
];
// // Enables High Res mode (Retina Display) on iPhone 4 and maintains low res on all other devices
if( ! [director enableRetinaDisplay:YES] )
CCLOG(#"Retina Display Not supported");
#if GAME_AUTOROTATION == kGameAutorotationUIViewController
[director setDeviceOrientation:kCCDeviceOrientationPortrait];
#else
[director setDeviceOrientation:kCCDeviceOrientationLandscapeLeft];
#endif
[director setAnimationInterval:1.0/60];
[director setDisplayFPS:NO];
[director setDepthTest:NO];
// make the OpenGLView a child of the view controller
[viewController setView:glView];
// make the View Controller a child of the main window
[window addSubview: viewController.view];
[window makeKeyAndVisible];
// Default texture format for PNG/BMP/TIFF/JPEG/GIF images
// It can be RGBA8888, RGBA4444, RGB5_A1, RGB565
// You can change anytime.
[CCTexture2D setDefaultAlphaPixelFormat:kCCTexture2DPixelFormat_RGBA8888];
// Removes the startup flicker
[self removeStartupFlicker];
// Run the intro Scene
[[CCDirector sharedDirector] runWithScene: [Intro scene]];
}
- (void)applicationWillResignActive:(UIApplication *)application {
[[CCDirector sharedDirector] pause];
}
- (void)applicationDidBecomeActive:(UIApplication *)application {
[[CCDirector sharedDirector] resume];
}
- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application {
[[CCDirector sharedDirector] purgeCachedData];
}
-(void) applicationDidEnterBackground:(UIApplication*)application {
[[CCDirector sharedDirector] stopAnimation];
}
-(void) applicationWillEnterForeground:(UIApplication*)application {
[[CCDirector sharedDirector] startAnimation];
}
- (void)applicationWillTerminate:(UIApplication *)application {
CCDirector *director = [CCDirector sharedDirector];
[[director openGLView] removeFromSuperview];
[viewController release];
[window release];
[director end];
}
- (void)applicationSignificantTimeChange:(UIApplication *)application {
[[CCDirector sharedDirector] setNextDeltaTimeZero:YES];
}
- (void)dealloc {
[[CCDirector sharedDirector] end];
[window release];
[super dealloc];
}
#end
try this line of code at
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:
[director setProjection:kCCDirectorProjection2D];
hope this will fix your issue.

My Cocos2d CCMenu won't responding to touch

Hi there when my game reaches it's Game Over Scene i have a button to return to the Main menu and for some reason this has stopped working
Here is the code that leads to my Game Over Scene:
[[CCDirector sharedDirector] pause];
[[CCDirector sharedDirector] replaceScene:[ResultsScreen node]];
In my Init function for Game Over
....
mainMenu = [CCMenuItemImage itemFromNormalImage:#"MainMenu.png" selectedImage:#"MainMenuClick.png" target:self selector:#selector(Menu:)];
[mainMenu setAnchorPoint:ccp(0.0f, 0.0f)];
menu = [[CCMenu menuWithItems:mainMenu, nil] retain];
menu.isTouchEnabled = YES;
[menu setPosition:ccp(75, 80)];
[menu setAnchorPoint:ccp(0, 0)];
[self addChild:menu z:Z_INTERACTION];
....
My Selector Function for the button
- (void) Menu:(id)sender
{
NSLog(#"Exit to MainMenu");
[[CCDirector sharedDirector] replaceScene:[MainMenu node]];
}
Now I've compared this with my other code, all my other buttons are working, the only difference is that is that i am specifying a 'z' value.
Any help would be very much appreciated
Update:
Ran a quick check with Leaks and Allocations and nothing seems to be an issue
I found my Issue in my - (void) onEnter {}
I wasn't calling [super onEnter];

Resources