Tuesday, July 17, 2012

Cocos2d Changing Scene for Noob

Ok, So today I learned about how to change scene from one layer to another

so let say you are in scene1, how do you change to scene 2?

First Step: Creating Scene 2
1. Right click your project, add new file
2. select Cocos2d file, the "CCNODES class"
3. subclass of "CCLAYER"
4. give a name, let say "MainMenuLayer"
5. double click your MainMenuLayer.h and add

+(CCScene *) scene;

6.double click your MainMenuLayer.m and add

-(id) init
{
    
    if( (self=[super init] )) {
        
        CCLabelTTF *title = [CCLabelTTF labelWithString:@"Main Menu" fontName:@"Courier" fontSize:64];
        title.positionccp(240, 240);
        [self addChild: title];
        
    }
    return self;
}

- (void) dealloc
{
    
    [super dealloc];
}

// Helper class method that creates a Scene with the HelloWorldLayer as the only child.
+(CCScene *) scene
{
// 'scene' is an autorelease object.
CCScene *scene = [CCScene node];
// 'layer' is an autorelease object.
MainMenuLayer *layer = [MainMenuLayer node];
// add layer as a child to scene
[scene addChild: layer];
// return the scene
return scene;
}

Explanation- Well, you need to first init your scenes with some label "MAIN MENU", you will also need to dealloc your scene if not been used, also finally is the scene function that can be called by the CCDIRECTOR

now you have successfully created a scene 2 you can proceed to next step



Second Step: Calling Scene 2 from Scene 1
1. Open your scene1.m, paste the header of your scene2

#import "MainMenuLayer.h"

2. Under any function that you want to switch scene to scene 2, paste this code

[[CCDirector sharedDirector] replaceScene:[MainMenuLayer scene]];

Done, thats it
Let say you put the code under ccTouchEnded
Then the moment you tab your app it will go the scene2, and you can do the same to go back to scene1


Additional info:(just in case you have not configured ccTouchEnded, this is how you do it)
1. on your scene.m , paste this on top
#import "CCTouchDispatcher.h"
2. on your scene.m under init function
self.isTouchEnabled = YES;
3. Paste this 3 function on your scene.m
-(void) registerWithTouchDispatcher
{
[[CCTouchDispatcher sharedDispatcher] addTargetedDelegate:self priority:0 swallowsTouches:YES];
}

- (BOOL)ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event {
    return YES;
}

- (void)ccTouchEnded:(UITouch *)touch withEvent:(UIEvent *)event {
CGPoint location = [self convertTouchToNodeSpace: touch];
    
    
    
}


That it, now you can paste any code under ccTouchEnded and once you touch your app it will react, Example you put this under the ccTouchEnded

[[CCDirector sharedDirectorreplaceScene:[YOUSCENE scene]];










No comments:

Post a Comment