Understanding Scene


What is Scene? 
  • A scene (implemented with the CCScene object) is more or less an independent piece of the app workflow.
  • One of the building blocks of a cocos2d is the Scene.
  • Game made up of "game screens" called Scenes.
  • Cocos2D games are made up of scenes (CCScenes), and the director (CCDirector) is responsible for running Scenes.
  • Director handles main window and executes Scenes.
  • The Cocos2D Director runs only one Scene at a time.
  • Each scene in Cocos2D consists of one or more layers, which are composited on top of each other.




You can define every one of these scenes more or less as separate apps; there is a bit of glue between them containing the logic for connecting scenes.

 A cocos2d CCScene is composed of one or more layers (implemented with the CCLayer object), all of them piled up. Layers give the scene an appearance and behavior; the normal use case is to just make instances of Scene with the layers that you want.

There is also a family of CCScene classes called transitions (implemented with the CCTransitionScene object) which allow you to make transitions between two scenes (fade out/in, slide from a side, etc).

Since scenes are subclasses of CCNode, they can be transformed manually or by using actions.

Working Example


GameScene.h
#import "cocos2d.h"

@interface GameScene : CCScene {}
@end

// Extending CCColorLayer so that we can specify a 
// default background color other than black 
@interface GameLayer : CCColorLayer {}
@end

GameScene.m

#import "GameScene.h"
#import "HelloWorldScene.h"

@implementation GameScene

- (id)init
{
 if ((self = [super init]))
 {
 // All this scene does upon initialization is init & add the layer class
  GameLayer *layer = [GameLayer node];
  [self addChild:layer];
 }
 
 return self;
}

- (void)dealloc
{
 // Nothing else to deallocate
 [super dealloc];
}

@end


To navigate through your game’s UI, you’ll make calls to the cocos2d Director singleton to replace the currently active scene; something like

[[CCDirector sharedDirector] replaceScene:[GameScene node]]; 

Most likely this call would be in a method that is run in response to a button being tapped, or after a level is completed so the player can return to a level select screen. You can also switch your scenes using some nifty transition effects that are built in to cocos2d. These are called like so:

[[CCDirector sharedDirector] replaceScene:[CCFlipXTransition transitionWithDuration:0.75 scene:[GameScene node]]];

No comments:

Post a Comment