Proper cocos2d scene restart? - objective-c

How do I restart cocos2d scene and clean memory after the previous one?
[director replaceScene:s] is displaying pink screen. Can't get it to work.
The work-around I made is below, however after closing scene this way app runs very slow and slowly reacts to touch. MainViewController.m:
- (IBAction)startScene {
[CCTexture2D setDefaultAlphaPixelFormat:kTexture2DPixelFormat_RGBA8888];
if ([director runningScene]) {
[director end];
works = NO;
}
if (!works) {
EAGLView *glview = [EAGLView viewWithFrame:CGRectMake(0,0, 768, 1024)];
[self.view addSubview:glview];
[director setOpenGLView:glview];
CCLayer *layer = [PlayLayer node];
CCScene *s = [CCScene node];
[s addChild: layer];
[director runWithScene:s];
}
}
Inside PlayLayer.m I go back from scene to view using:
CCDirector *d = [CCDirector sharedDirector];
EAGLView *v = [d openGLView];
[v removeFromSuperview];
Application is displaying images (1280x960x32, imageview inside scrollview) and when user presses the button he can start cocos2d scene. User can then leave from scene back to view (.xib) and continue browsing through images till he finds a new one to start scene with.
I believe this is not a good way to leave scene but everything else I tried is causing app to crash or I keep getting this pink screen 2nd time I start scene. How do I restart it ?

I finally could get rid of pink screen while replacing scene. This is how I am doing it. While adding scene, I check if it's running first time or subsequent times.
MyTestAppDelegate * appDelegate = (MyTestAppDelegate *)[[UIApplication sharedApplication] delegate];
EAGLView *glView;
//check if scene is running first time then create OpenGLView, add to director and run the scene
if ([[CCDirector sharedDirector] runningScene] == NULL) {
if( ! [CCDirector setDirectorType:kCCDirectorTypeDisplayLink] )
[CCDirector setDirectorType:kCCDirectorTypeDefault];
CCDirector *director = [CCDirector sharedDirector];
glView = [EAGLView viewWithFrame:[appDelegate.window bounds]
pixelFormat:kEAGLColorFormatRGB565 // kEAGLColorFormatRGBA8
depthFormat:0 // GL_DEPTH_COMPONENT16_OES
];
[director setOpenGLView:glView];
[director setDeviceOrientation:kCCDeviceOrientationPortrait];
[director setAnimationInterval:1.0/60];
[director setDisplayFPS:YES];
[appDelegate.window addSubview:glView];
[[CCDirector sharedDirector] runWithScene: [MyScene node]];
}
//if scene is to be reloaded, add back the openGLView which was removed when removing the scene
else {
[appDelegate.window addSubview:[[CCDirector sharedDirector] openGLView]];
[[CCDirector sharedDirector] replaceScene:[MyScene node]];
}
For removing currently running scene:
[[CCDirector sharedDirector] replaceScene:[MySceneTwoLayer scene]];
[[CCDirector sharedDirector].openGLView removeFromSuperview];
Adding MySceneTwoLayer is optional. It is an empty scene. I am using it to make sure previous scene was properly removed. And I checked, previous scene's dealloc is properly called.
I hope it helps.

I came across a simliar problem when using Storyboards and when returning to m original UI view which contained my CCGLView from another view.
//when leaving the scene containing the CCGLView.
[CCDirector director] popScene];
then I noticed in viewDIdLoad for that viewcontroller, it would go through this when reinstantiated bt the segue, where you can re add the scene again.
// in viewDidLoad
[CCDirector director] pushScene: theSceneIRemovedEtc];
Admititedly this mightnot work for all cases but certainly did for me..

Ok, found a solution that closes the scene from inside and works well.
While starting scene I add the notification observer in my viewcontroller:
(...)
[director runWithScene:s];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(mySceneEnd:) name:#"scene_ended" object:nil];
That is connected to:
- (void) mySceneEnd:(NSNotification *)notif {
if ([director runningScene])
[director end];
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
Then in the scene ending method I'm sending the notification to my viewcontroller:
EAGLView *v = [[CCDirector sharedDirector] openGLView];
[v removeFromSuperview];
[[NSNotificationCenter defaultCenter] postNotificationName:#"scene_ended"
object:nil userInfo:nil];
Works really nice, app runs fast after closing scene, but it's an old question/answer and there is surely a better way to do it now.

Related

How can load a cocos2d scene from view controller class?

1)I made a game using cocos2d-iphone v3.
2)I integrated a fullscreen advertisement.
3)I want to load a cocos2d scene, when user closes ad, but it doesn't work(I imported cocos2d framework).There is just a black screen after advertisement disappears with animation. "interstitialAdDidFINISH" appears in the output, so most likely, that last line is wrong.
-(void)interstitialAdActionDidFinish:(ADInterstitialAd *)interstitialAd {
interstitial = nil;
// [interstitialAd release];
// [ADInterstitialAd release];
requestingAd = NO;
NSLog(#"interstitialAdDidFINISH");
[[CCDirector sharedDirector] replaceScene:[CCBReader loadAsScene:#"MainScene"]];
}
I guess, that I can't load a cocos2d scene from UIViewController class so easy.....
How can I do this?
EDIT: So ? It's not nil
if ( [CCDirector sharedDirector].view != nil) {
NSLog(#"Hey there");
}
EDIT 2: I found out, that [CCDirector sharedDirector]]; is a ViewController too.
I tried something like this . The game crashes, after iAd finished.
[self addChildViewController:[CCDirector sharedDirector]];
[self presentModalViewController:[CCDirector sharedDirector] animated:NO];
[[CCDirector sharedDirector] replaceScene:[CCBReader loadAsScene:#"MainScene"]];
I'v found solution. May be helpfull for others.
First, that's, how I present iad view controller from the MainScene
*ViewControllerAdEx= [[ ViewControllerAd alloc] init]; // making an instance of iad class
[[CCDirector sharedDirector] presentModalViewController:ViewControllerAdEx animated:YES];
[ViewControllerAdEx showFullScreenAd]; // caling a method from class
In the iad class, when iad finishes work:
[self dismissViewControllerAnimated:YES completion:^{
[[CCDirector sharedDirector] replaceScene:[CCBReader loadAsScene:#"MainScene"]];
}];

Cocos2d v3 CCButton conflicting with UIGestureRecognizers

I've added a UIGestureRecognizer to a class which hinerits from NSObject, and I'm handling the gestures with the UIGestureRecognizers, but I need to add an upper layer and add some CCButton on it, so to conceptualize my hierarchy would be pretty much this:
- CCScene
-- CCNode added to the scene (with the gesture recognizers)
-- another CCNode added with a few CCButton
the UIGestureRecognizers are working well, but the CCButton is never called because the touch is handled by the gestures, if I remove the gestures, the CCButton is called
they are in conflict and I don't know why, I've read that the CCNodes touches are swallowed starting from the first (in term of hierarchy, where the first is the bigger z order I think) until the last, so since both my CCNode are added to the scene, and since the second ccnode (added with a bigger z order) is the first I think it should get the touch BEFORE the UIGestureRecognizer of the other ...
what I'm missing?
here's how I've added the gestures:
UITapGestureRecognizer *myGesture = [[UITapGestureRecognizer alloc] initWithTarget:self.myClassImplementation action:#selector(gesture:)];
[tapGesture setDelegate:self.myClassImplementation];
[[[CCDirector sharedDirector] view] addGestureRecognizer:myGesture];
I tried to simply add the CCButton directly into the CCScene but isn't called, can someone explain to me why they are in conflict? so to find I way to make it works
Gesturerecognizers get all the standard responder touch events. So you should handle it in gesturerecognizer's delegate method or in gesture action.
Here is how you can do it in delegate method:
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
CGPoint touchLocation = [[CCDirector sharedDirector] convertToGL: [touch locationInView:touch.view]];
CCResponderManager *responder = [[CCDirector sharedDirector] responderManager];
CCNode *node = [responder nodeAtPoint:touchLocation];
if([node isKindOfClass:[CCButton class]])
{
NSLog(#"button");
return NO;
}
else
{
NSLog(#"not button");
return YES;
}
}

cocos2d with view controller

I am using cocos2d and view controllers in my game. I wants to call a view controller using cocos2d scene using following code
PlayAgainViewController* playAgain = [[PlayAgainViewController alloc] initWithNibName:#"PlayAgainViewController" bundle:nil];
[[[CCDirector sharedDirector] openGLView] addSubview:playAgain.view];
its adding view controller view on game scene but not calling another view controller by using view added on openGl view.
//if UR_COCOS2D_VERSION_2_0
AppController *app = (AppController*)[[UIApplication sharedApplication] delegate];
[app.navController presentModalViewController:playAgain animated:YES];
//Cocos2D 1.0, use viewController property in appDelegate.
AppDelegate* app = (AppDelegate*)[[UIApplication sharedApplication] delegate];
[app.viewController presentModalViewController:playAgain animated:YES];
Thanks a lot for your answer.as :
[[CCDirector sharedDirector] pause];
PlayAgainViewController* playAgain = [[PlayAgainViewController alloc] initWithNibName:#"PlayAgainViewController" bundle:nil];
AppDelegate* app = (AppDelegate*)[[UIApplication sharedApplication] delegate];
[app.navigationController pushViewController:playAgain animated:YES];
it helps me a lot and solved my problem.
But now i am facing a new problem which is when i am calling view controller from cocos2d layer using your answer its working excellent :), but when i want to call another view controller which is calling EAGLView usig following code:
if([[CCDirector sharedDirector] isPaused])
[[CCDirector sharedDirector] replaceScene:[Game scene]];
else
[[CCDirector sharedDirector] runWithScene:[Game scene]];
its showing white screen. I think the problem is texture. Can u please tell me how to release textures used in layer while calling view controller.

get the current scene returns NULL?

I am trying to reload the current scene , and the init is happen then dealloc .
i want to have a condition on the dealloc to return back if it called from the current scene.
i was trying this :
if ([[[CCDirector sharedDirector] runningScene] getChildByTag:16])
return;
and
[[[CCDirector sharedDirector] runningScene] isKindOfClass:[HelloWorldLayer class]]
both gives me NULL, and condition is not true.
why is that ???
my scene looks like :
+(CCScene *) scene
{
// 'scene' is an autorelease object.
CCScene *gameScene = [CCScene node];
// 'layer' is an autorelease object.
HelloWorldLayer *layer = [HelloWorldLayer node];
layer.tag=16;
// add layer as a child to scene
[gameScene addChild: layer];
// return the scene
return gameScene;
}
how can i eliminate the dealloc when i only refresh the scene ??
Never do this:
[[CCDirector sharedDirector] replaceScene:self]
or this:
CCDirector* director = [CCDirector sharedDirector];
[director replaceScene:director.runningScene];
You can not replace the current scene simply by passing self or the currently running scene to the replaceScene method. You always have to create a new instance of your CCScene class:
[[CCDirector sharedDirector] replaceScene:[MyScene scene]]
Be careful with the runningScene. The first time you send the runWithScene message to the director, the runningScene will always be nil. You can defer some initialization to the onEnter method:
-(void) onEnter
{
// runningscene is valid in onEnter
[[CCDirector sharedDirector] runningScene];
[super onEnter];
}

Add cocos2d scene to UIViewController

I use the following code to add cocos2d scene to a viewcontroller
- (void)viewDidLoad {
self.view = [[UIView alloc] initWithFrame:CGRectMake(0,0,320,480)];
if( ! [CCDirector setDirectorType:CCDirectorTypeDisplayLink] )
[CCDirector setDirectorType:CCDirectorTypeDefault];
[[CCDirector sharedDirector] setPixelFormat:kPixelFormatRGBA8888];
[CCTexture2D setDefaultAlphaPixelFormat:kTexture2DPixelFormat_RGBA8888];
[[CCDirector sharedDirector] setDeviceOrientation:kCCDeviceOrientationPortrait];
[[CCDirector sharedDirector] setAnimationInterval:1.0/60];
[[CCDirector sharedDirector] attachInView:self.view];
///adding HelloWorld scene to the view...
[[CCDirector sharedDirector] runWithScene: [HelloWorld scene]];
[super viewDidLoad];
}
And now i need to set the alpha value of self.view....so i did it..
-(void)displaySharePage
{
self.view.alpha=0;
}
But it crashed......don't know why....i got the message..
'A Director was alloced.
setDirectorType must be the first call
to Director'
can anyone help.....advance thanks..
attachInView will be deprecated. Try using setOpenGLView instead. http://www.cocos2d-iphone.org/api-ref/latest-stable/interface_c_c_director.html#a87f9460b05b18b5c7726e1bdcbfe3eca
From the error, it looks like one of two things is happening:
viewDidLoad is being called more than once. You can check this by adding a log statement or breakpoint at the beginning of the method. This will help you find the root cause. You have to make sure that the director code is only called once. One way (not necessarily the right way) is to move the [CCDirector setDirectorType:] call to your app delegate.
You are calling [CCDirector setDirectorType:] somewhere else in your code. This seems unlikely, but doing a search for it would be helpful.
maybe its really getting called twice?
#synthesize window;
- (void)loadView {
// Initialization code
CC_DIRECTOR_INIT();
CCDirector *director = [CCDirector sharedDirector];
//landscape
[director setDeviceOrientation:kCCDeviceOrientationPortrait];
[director setDisplayFPS:YES];
//turn on multi-touch
EAGLView *cocosView = [director openGLView];
[cocosView setMultipleTouchEnabled:YES];
self.view = cocosView;
//default texture formats...
[CCTexture2D setDefaultAlphaPixelFormat:kTexture2DPixelFormat_RGBA8888];
[[CCDirector sharedDirector] runWithScene:[MainGame scene]];
}