Cocos2d Tips: Sounds & Text

Professionalize your game by adding sounds and text for menus and labels throughout your game.

Sound Creates Impacts!
Sound Creates Impacts!


To play sounds you need the Sound Engine, which you import into your layer like so:

#import “SimpleAudioEngine.h”

Then you can just code a method to handle some background music playing:

-(void)loadAudio {

// Loading Sounds Synchronously

[CDSoundEngine setMixerSampleRate:CD_SAMPLE_RATE_MID];

[[CDAudioManager sharedManager] setResignBehavior:kAMRBStopPlay


soundEngine = [SimpleAudioEngine sharedEngine];

[soundEngine preloadBackgroundMusic:BACKGROUND_MUSIC];

[soundEngine playBackgroundMusic:BACKGROUND_MUSIC];


You can see immediately that you can preload the audio in one place and then play it in another. This is great for game performance. This means you can preload audio in the main menu, for example, and then play it when you actually need it.

Another way to put this into perspective is to preload an audio when an object such as an enemy ship or main player is created and then play the specific sound when his state is changed. For example, if you create a main player class which manage the player’s state between walking, jumping, running, flying…you can make the calls to play different sound effects when the player’s state changes.

For example;

-(void)changeState:(CharacterStates)newState {

// stop all, nil action, nil move, newPosition ivar, set new state passed into it…

[self stopAllActions];

id action = nil;

[self setCharacterState:newState];

switch (newState) {

case kStateFlying:

action = [CCAnimate actionWithAnimation:flyingAnim];




} // ends the switch that checks for state

if (action != nil) {

[self runAction:[CCRepeatForever actionWithAction:action]];



You can also get more sophisticated and preload audio into your layer using plists for lists of files which are loaded as soon as the scene is loaded. We will look at this in the Advanced flavor of this post!

Text is Terrific!
Text is Terrific!


Now let’s move on to some text. One of my favorite places to add text is at the beginning of a layer when the game is about to start. For this we create a label like so:

CGSize winSize = [CCDirector sharedDirector].winSize;

label = [CCLabelTTF labelWithString:@”hello!” dimensions:CGSizeMake(300, 250) hAlignment:UITextAlignmentCenter fontName:@”Stencil” fontSize:40];

label.color = ccc3(000,000,000);

label.position = ccp(winSize.width/2, winSize.height/2);

This creates a simple label which you can place anywhere on the screen, change its color etc. Let’s say you also wanted to animate this label, you could string this along at the bottom:

CCScaleTo *scaleUp = [CCScaleTo actionWithDuration:2.5 scale:1.8];

CCScaleTo *scaleBack = [CCScaleTo actionWithDuration:0.5 scale:1.5];

CCDelayTime *delay = [CCDelayTime actionWithDuration:3.0];

CCFadeOut *fade = [CCFadeOut actionWithDuration:1.5];

CCHide *hide = [CCHide action];

CCSequence *sequence = [CCSequence actions:scaleUp, scaleBack, delay, fade, hide, nil];

[label runAction:sequence];

Cool! Now you’ve got the workings of some awesome eye candy for your games.

Cocos2d Tips: Design Game Objects for your game


Keep your game classes organized and logically ordered. Create a GameObject class, a GameCharacter class and then subclass these.

Its important to keep your Game Objects ordered as well as your code.  The more you order your objects, the cleaner your code will be as well.  A GameObject is anything used in a game from labels to sprites to power ups.

Its important to create a base class for all objects because, as a simple example, you want to be able to constrain all game objects to your screen.  Its not unthinkable to believe that at some point you might inadvertently cause a game object to be pushed off screen.  Thus it would be nice to have a method, something like keepObjectInBounds, to make sure you can call it on any or all objects to make sure they are not halfway or all the way offscreen.

After you build you base class, GameObject, you will subclass it to build objects.  But you can also subclass GameObject to build functionally similar types of objects like a Powerups subclass or an Enemy subclass.  For example, you might want all Powerup class objects to have a setAutoDestroyTime method that gives any object of that class a specific time to live onscreen before it disappears.

So let’s look at init methods, designated initializers, self and super.

You can create a GameObject Class in 1 file set or in different file sets.  This is where self and super take hold in your brain.  Self means, that very same class you are currently in.  Super means its super or parent class.  For example, lets say we create this hierarchy:

  1. GameObject (Everything is a GameObject)
    1. GameCharacter (Distinguish between GameCharacters and GamePowerUps)
      1. GameEnemy (Some GameCharacters are bad and some are good)
        1. GameBigBossEnemy
      2. GamePlayer
        1. GamePlayerHero 
        2. GamePlayerFriend
    2. GamePowerup

GameCharacter is a subclass of GameObject.  Which is to say, GameObject is the parent of GameCharacter.  This makes sense because your GameObjects may be characters that have a personality and animation and perform actions.  But some GameObjects will just sit there, like trees and clouds.  Clouds may be moved by wind and that is about it!  But a GamePlayer, our hero, needs to have a lot more internal logic, his own Artificial Intelligence logic if you will.

By the same token, GamePlayer may include our hero instance but it may also include a friend instance, which may be like his sidekick or something.  The logic for a friend will not include any methods to follow or attach our hero, whereas enemies will have to have that sort of logic.

This is the reason we subclass objects, in order to use a base functionality for all (all game objects must remain onscreen at all times) but give specific functionality to others (followMainPlayer method).

Lets say you’re inside GamePlayerHero and you are coding away.  If you say

[self blowHisNose];

You are calling the blowHisNose method which should exist in our GamePlayerHero class.  If it doesn’t exist in self, that object will look to its super for a corresponding method.  You don’t need to call:

[super blowHisNose];

That is what object inheritance in OOP is all about.  So if the method doesn’t exist in GamePlayerHero, the hero object looks to its parent class or super class, GamePlayer.  If GamePlayer doesn’t have that method then it will keep going until it finds that method.  If it doesn’t, your game will crash :).

So lets take a look at a practical example, an initializer.  An initializer is just another name for a Class’ init method.  Every class must have an init method.  Here is a typical one:

-(id) init {

if((self=[super init]);


return self;


This means, if this class is equal to super’s init, then do this and return self.  Since a class will always have a super class, this basically says, if I have a super class (which is always) then return myself.

Now if a child class (lets call it GameCharacter class) of this previous class (GameObject class) wants to add functionality to its parent class, then it will NOT OVERRIDE its parent class methods, it will simply add methods.  So the new GameCharacter class could just have a method like this:

-(void)checkAndClampSpritePosition {

CGPoint currentSpritePosition = [self position];

CGSize levelSize = [[GameManager sharedGameManager]


float xOffset;

if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {

// Clamp for the iPad

xOffset = 30.0f;

} else {

// Clamp for iPhone, iPhone 4, or iPod touch

xOffset = 24.0f;


if (currentSpritePosition.x < xOffset) {

[self setPosition:ccp(xOffset, currentSpritePosition.y)];

} else if (currentSpritePosition.x > (levelSize.width – xOffset)) {

[self setPosition:ccp((levelSize.width – xOffset),




Which says, Im not initializing anything (because if it does, it will erase its parent’s init method), Im just adding this method to any instance of GameCharacter AND every instance of GameCharacter will still have to be initialized from GameObject’s init.

Let’s see a more practical example.  Let’s look at an Enemy Class which can generate many different kinds of instances, all from the same code:

@interface ShipTarget : CCSprite {

int _curHp;

int _minMoveDuration;

int _maxMoveDuration;

NSString *filename;


@property (nonatomic, assign) int hp;

@property (nonatomic, assign) int minMoveDuration;

@property (nonatomic, assign) int maxMoveDuration;

@property (nonatomic, retain) NSString *filename;


@interface Asteroid : ShipTarget {




This says, Im a ShipTarget class and my instances will all be based off of CCSprite.  This means all my instances will have any methods and properties of CCSprite unless I override them (create new ones).  At the same time, I wish to create an Asteroid class which derives from this ShipTarget class and it will return an object by calling its class method named target.  Then in its implementation you have:

@implementation ShipTarget

@synthesize hp = _curHp;

@synthesize minMoveDuration = _minMoveDuration;

@synthesize maxMoveDuration = _maxMoveDuration;

@synthesize filename;


@implementation Asteroid

+ (id)target {

Asteroid *target = nil;

if ((target = [[[super alloc] initWithFile:@”Comet.png”] autorelease])) {

target.hp = 1;

target.minMoveDuration = 2;

target.maxMoveDuration = 4;


return target;



Notice again, the use of self, or target.  If there is such a thing returned from calling target’s super class, (target is ShipTarget class and ShipTarget’s super class is CCSprite) initWithFile… then set those properties and return it.  There is such a thing as target’s super class initWithFile method.  CCSprite has an initWithFile method.  Don’t believe me?  Then don’t, right click over initWithFile and select Jump to Definition and watch Xcode take you to CCSprite:

-(id) initWithFile:(NSString*)filename

 So we set the properties hp, min and maxMoveDuration.  Even though those properties don’t exist in CCSprite, they exist in the new subclass, ShipTarget.  We added them ourselves in the interface and later synthesized them in the implementation file.  Since target is of Asteroid class (which is itself type of ShipTarget), it therefore must have ShipTarget properties hp, min and maxMoveDuration.  This also means that any ShipTarget target we create, will have those 3 properties and we can set it.
This is very handy when creating the different GameObjects we discussed because they can all be based on a set of properties common to all enemies, or to all players, or to all powerups etc.  This saves you time when creating subclasses because you don’t have to create repetitive code for each object type.  And more importantly, it keeps your code tidy because if you need to add a property to all enemies, you simply add it to ShipTarget and voila…all your enemy targets will now have that property for you to assign.

Cocos2d Tips: Scrolling, Parallax and wider levels

Wider Levels & Scrolling

When you create a game in Cocos2d, your screen measures 960 pixels wide on iPhone4+ and 2048 on iPad. If we want him to move farther to the right then we need to make the level bigger.  Normally we set:

levelSize = screenSize;

But now we basically wish to make:

levelSize = CGSizeMake(screenSize.width * 2.0f, screenSize.height); // levelSize code

What we are doing is changing our scene levelSize to 2x the screenSize.

Our level is now twice as big and we have a GameScene, which contains a GameplayLayer & a BackgroundLayer with some background image.  We want to add a layer that will scroll in the opposite direction as our player moves.  To do this we will need to add a method a method called adjustLayer:

-(void)adjustLayer {

Player *player = (Player*)[sceneSpriteBatchNode getChildByTag:kPlayerSpriteTagValue];

float playerXPosition = player.position.x;

CGSize screenSize = [[CCDirector sharedDirector] winSize];

float halfOfTheScreen = screenSize.width/2.0f;

CGSize levelSize = [[GameManager sharedGameManager] getDimensionsOfCurrentScene];//1

if ((playerXPosition > halfOfTheScreen) && (playerXPosition < (levelSize.width – halfOfTheScreen))) {

// then scroll background

float newXPosition = halfOfTheScreen – playerXPosition;

[self setPosition:ccp(newXPosition,self.position.y)];      // 2 self is the game layer



Here comment //1 is a call to a method which returns the desired levelSize.  Or you can simply hard code it in this case by replacing this line with the //levelSize code line from above.  Remember we are running this method in the GameplayLayer, which is self in this code.  This needs to be called constantly so you must add this line to your update layer.  What we are doing here is keeping the screen centered on the player.  Now in the update method add this code:

//1. Get the list of objects on the layer & loop through them

CCArray *listOfGameObjects = [sceneSpriteBatchNode children];

for (GameCharacter *tempChar in listOfGameObjects) {

[tempChar updateStateWithDeltaTime:dt andListOfGameObjects:listOfGameObjects];


//2. Call the adjustLayer method

[self adjustLayer];

Perfect!  Now let’s add the image that is actually going to scroll.  Add this method to your GameplayLayer.m:

-(void)addScrollingBackground {

CGSize screenSize = [[CCDirector sharedDirector] winSize];

CGSize levelSize = [[GameManager sharedGameManager] getDimensionsOfCurrentScene];

CCSprite *scrollingBackground;

if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {

// Indicates game is running on iPad

scrollingBackground = [CCSprite spriteWithFile:@”mars_landscape2x.png”];

} else {

scrollingBackground = [CCSprite spriteWithFile:@”mars_landscape2x.png”];


[scrollingBackground setPosition:ccp(levelSize.width/2.0f,screenSize.height/2.0f)];

[self addChild:scrollingBackground z:1];


In order for this to appear, we need to call it from the init method by adding this line:

[self addScrollingBackground];

Let’s review.  addScrollingBackground adds a new image to the GameplayLayer.  (This image is positioned over the true background, which is in the BackgroundLayer.)  Therefore, the new image you add here should be a sort of rocky ground floor that will slide sideways as the player moves.

Make sure the image is twice as big as the screen so there will be enough of it to scroll through as the player moves.

Now Build & Run and watch your ground scroll differently as your background as your player moves left or right.


Parallax makes one layer scroll faster or slower than the other.  It’s quite easy to achieve this effect.  First add a new instance variable to your GameplayLayer.m file like so:

@implementation GameplayLayer {

CCParallaxNode *parallaxNode;


NOTE: We are extending the @implementation line to include an ivar.  No need to declare it in the @interface file.  Remember .h files (header files) only need to include what properties or methods you want your object to expose to other calling objects.

And now replace your addScrollingBackground method with this one:

// Scrolling 3 Parallax backgrounds

-(void)addScrollingBackgroundWithParallax {

CGSize screenSize = [[CCDirector sharedDirector] winSize];

CGSize levelSize = [[GameManager sharedGameManager]


CCSprite *BGLayer1;

CCSprite *BGLayer2;

CCSprite *BGLayer3;

if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {

// Indicates game is running on iPad

BGLayer1 = [CCSprite spriteWithFile:@”mars_landscape2x.png”];

BGLayer2 = [CCSprite spriteWithFile:@”some_rocks.png”];

BGLayer3 = [CCSprite spriteWithFile:@”some_pillars.png”];

} else {

BGLayer1 = [CCSprite spriteWithFile:@” mars_landscape2x.png”];

BGLayer2 = [CCSprite spriteWithFile:@” some_rocks.png”];

BGLayer3 = [CCSprite spriteWithFile:@” some_pillars.png”];


parallaxNode = [CCParallaxNode node];

[parallaxNode setPosition:ccp(levelSize.width/2.0f,screenSize.height/2.0f)];

float xOffset = 0;

// Ground moves at ratio 1,1

[parallaxNode addChild:BGLayer1 z:40 parallaxRatio:ccp(1.0f,1.0f) positionOffset:ccp(0.0f,0.0f)];

xOffset = (levelSize.width/2) * 0.3f;

[parallaxNode addChild:BGLayer2 z:20 parallaxRatio:ccp(0.2f,1.0f) positionOffset:ccp(xOffset, 0)];

xOffset = (levelSize.width/2) * 0.8f;

[parallaxNode addChild:BGLayer3 z:30 parallaxRatio:ccp(0.7f,1.0f) positionOffset:ccp(xOffset, 0)];

[self addChild:parallaxNode z:10];


Don’t forget to change the GameplayLayer’s init method call to:

[self addScrollingBackgroundWithParallax];

What we are doing now is adding more layers and offsetting their center positions.  Thus when they move, they will move at different rates.  Build & run the app.

You can use scrolling to add clouds or stars or alien birds to make some eyecandy for your users.  If you choose to scroll many objects on the screen though, you might want to look into reusing them.  This is a very popular technique used to improve performance of a game.  You create one instance of the object at a time and add it to an array for tracking.  When that instance moves offscreen, you remove it from that array.  This saves you a lot of memory.

Cocos2d Tips: Transitioning between game screens

Let’s learn how to create menu for a cocos2d game and how to move between a menu, the game scene, a level complete scene etc.

Eventually your game will grow and you will have to create a clear structure to keep everything organized.


As you can see, as with any app, the AppDelegate is the first object called. As such, it is the entry point to your game and will call the very first scene of your game. This means the first scene should probably the main menu which welcomes the user to the game and presents him with options.

As you can see from the Cocos2d tips “Creating a Menu”, menus can be quite complex: ‎

When a cocos2d game is created, a Singleton instance of the GameDirector is instantiated and charged with managing scenes. After all, your Main Menu scene is just another scene/layer called by the game director. Thus it is quite common to create another Singleton class used to tell the director which scene to call.

Let’s call it the GameManager and his sole job is to tell the director which scene to call. Before we take a look at some code, keep in mind a game may grow to have quite a few scenes and while text is more human readable, it is easier to manage variables as numbers. The main reason is that switch statements use numbers, not text.

So it is common practice to use code such as this in a Constants.h file that you import into your GameManager.m Class:

typedef enum {





} SceneTypes;

Now you can easily use a method such as this:

-(void)runSceneWithID:(SceneTypes)sceneID {

SceneTypes oldScene = currentScene;

currentScene = sceneID;

id sceneToRun = nil;

switch (sceneID) {

case kMainMenuScene:

sceneToRun = [MainMenuScene node];


case kFirstScene:

sceneToRun = [Scene1 node];


case kSecondScene:

sceneToRun = [PlaneScene node];//[Escena2 node];//


case kThirdScene:

sceneToRun = [Scene3 node];



CCLOG(@”Unknown ID, cannot switch scenes”);




if (sceneToRun == nil) {

// Revert back, since no new scene was found

currentScene = oldScene;




if ([[CCDirector sharedDirector] runningScene] == nil) {

NSLog(@”runningScene is nil…its ok because we are in process of setting the new scene???”);

[[CCDirector sharedDirector] runWithScene:sceneToRun];

} else {

[[CCDirector sharedDirector] replaceScene:[CCTransitionFlipAngular transitionWithDuration:0.5f scene:sceneToRun]];


currentScene = sceneID;



Now this simple switch can be used to change scenes.  All you have to do at the end of the AppDelegate is call GameManager’s sceneToRun method and pass it the MainMenuScene.


At the Main Menu scene, depending on the level selected from the menu you can pass a particular scene constant to GameManager in order to determine the level scene to call.


From within your game level layer, after defining if your player won or lost, you can call GameManager to run a custom EndOfLevel scene/layer.  Then from that transitional scene you can call the MainMenuScene again.

Cocos2d Tips: Connect Layers

Games have many layers.


The most common example is the main action layer (where the players and enemies are) having to communicate with the HUD layer (which presents score, health and other info) to the gamer. Let’s see how we can communicate between layers.

Typically you create a Scene and then a Layer in order to add that Layer as a child to the Scene.

Let’s say our Scene.h looks like this:

#import <Foundation/Foundation.h>

#import “cocos2d.h”

@interface Scene1 : CCScene {



And our Scene.m looks like this:

-(id)init {

if ((self = [super init])) {

Scene1ActionLayer * actionLayer = [[[Scene1ActionLayer alloc] init] autorelease];

[self addChild:actionLayer z:0 tag:kActionLayer];


return self;


So we are adding the main action layer, actionLayer, to our scene at z=0 with a tag kActionLayer.  Simple enough.  Now let’s say we want to create a HUD layer to contain game information.  This can range from points, to level information, to instructions or simply health or powerup information.

Im not much of a designed so I created this simple rectangle as a bottom bar for my game.


The idea here is that those stars will actually represent the powerups a player must collect in order to complete a level.  Thus this will actually be a silhouette and each time the player picks up a power up, the HUD gets updated to place the powerup image in that space.  So we need the actionLayer to communicate with the HUD layer in order to say “Update the BIG GUNS power up!”.

We go ahead and create the actionLayer, possibly with a method called updateHUDWithPowerup:(Powerup*)power up; where Powerup is anything as simple as a typedef or as complex as a custom NSObject.

First, we need an instance of the HUD layer inside our actionLayer to call its method.  So inside our actionLayer, we forward declare it in our action layer :

@class “HUDLayer;

and then create an ivar for its instance:

HUDLayer *hudLayerInstance;

Second, we import the class in our action layer.m:

#import “HUDLayer.h”

Third, we simply allocate the instance in our actionLayer’s init method:

hudLayerInstance = [[HUDLayer alloc] initWithActionLayer:self];

[self addChild:backLayer z:0 tag:100];

Fourth, when the time comes to update the HUDLayer from the action layer’s update method (perhaps), we call:

[hudLayerInstance someMethodDefinedInHUDLayer:withThisValue];

Fifth, don’t forget to code the HUDLayer.  In its interface, forward declare your action layer class and add the custom initializer as well as your method like so:

@class ActionLayer;

@interface HUDLayer : CCLayer {

CCLabelTTF *_scoreLabel;


@property (nonatomic, assign) CCLabelTTF *scoreLabel;



Finally implement your initializer and its “someMethodDefinedInHUDLayer” in order to pass it “withThisValue”.

Voila!  Another option is using Delegates/Protocols.



In this case we are adding all children to the Scene.  In order to get them to communicate, we would need to have methods inside the Scene itself to call actions between objects.  I prefer the former method.  I leave this kind of setup for adding layers that don’t really do much, such as timers, background, eye candy etc.  They are still important layers, they just dont interact with the actionLayer much or at all.

iOS App or Cocos2d Game Design – Grand Scheme

A lot of programmers that are entering the iOS application or Cocos2d game arena are somewhat confused about the overall scheme of things. They can’t see the forest for the trees. I’m a very visual learner myself, which actually makes me a rather bad programmer. Actually it makes me a bad programmer because I’m slow to pick stuff up. I need to see the big picture and then dive into the details, not the other way around.

So I put together a simple image, for visual learners like myself, to understand how things operate. At this moment its a very simple image. I intend to update it constantly in order to grow it into more detail.

1) iOS – Vanilla Application

  1. An empty Application contains an AppDelegate Class (Object)
  2. The AppDelegate has a Window property.
  3. That window property presents a view controller with all the bells & whistles you put into it.
iOS Application Design by - Marcio Valenzuela
iOS Application Design by – Marcio Valenzuela

2) Cocos2d – Simple Game

  1. AppDelegate loads a CCScene
  2. CCScene contains typically 1 layer
  3. CCLayer init method calls an update method which runs repeatedly
  4. In CCLayer creates a Box2d world with listeners
Cocos2d Game Design by - Marcio Valenzuela
Cocos2d Game Design by – Marcio Valenzuela

Hope this helps! If you want to visually understand something else, let me know!

TexurePacker 3.0.1 is the best tool for sprite sheets

TexturePacker for Spritesheets by - Marcio Valenzuela
TexturePacker for Spritesheets by – Marcio Valenzuela


Spritesheets are a must these days, what with having to include so much eyecandy now that games for iOS are getting so sophisticated.  Even if not for performance issues, spritesheets are great for simply keeping assets organized in a game.  Add to that the easy to use AutoSD option which makes your HD or Retina Display assets as well as the non-Retina assets easy to manage, TP is by far the best tool for the job.

Whether you are a newbie or advanced developer, we highly recommend you pick it up asap.  You’ll see how easy it is to manage your assets and export them.  This is a tool that really makes your life a lot easier as a developer.  We use it on all our own projects as well as recommend it to all our students.

Get it today at

Cocos2d Tips: Creating a Menu

CCMenu by Santiapps - Marcio Valenzuela
CCMenu by Santiapps – Marcio Valenzuela

You can create a menu by creating label items or image items and passing them to a CCMenu object. A typical MainMenuScene.m file might look like this:

-(void)playScene:(CCMenuItemFont*)itemPassedIn {

if ([itemPassedIn tag] == 1) {

[[GameManager sharedGameManager] runSceneWithID:kIntroScene];

} else if ([itemPassedIn tag] == 2) {

[[GameManager sharedGameManager] runSceneWithID:kSecondScene];

} else if ([itemPassedIn tag] == 3) {

[[GameManager sharedGameManager] runSceneWithID:kThirdScene];

} else {

CCLOG(@”Unexpected item. Tag was: %d”, [itemPassedIn tag]);



-(void)displayMainMenu {

CGSize screenSize = [CCDirector sharedDirector].winSize;

if (sceneSelectMenu != nil) {

[sceneSelectMenu removeFromParentAndCleanup:YES];


// Main Menu

CCMenuItemImage *playGameButton = [CCMenuItemImage






CCMenuItemImage *optionsButton = [CCMenuItemImage






mainMenu = [CCMenu menuWithItems:playGameButton,optionsButton,nil];

[mainMenu alignItemsVerticallyWithPadding:screenSize.height * 0.059f];

[mainMenu setPosition:ccp(screenSize.width * 2,screenSize.height / 2)];

id moveAction =

[CCMoveTo actionWithDuration:1.2f

position:ccp(screenSize.width * 0.75f,

screenSize.height * 0.70f)];

id moveEffect = [CCEaseIn actionWithAction:moveAction rate:1.0f];

[mainMenu runAction:moveEffect];

[self addChild:mainMenu z:0 tag:kMainMenuTagValue];


-(void)displaySceneSelection {

CGSize screenSize = [CCDirector sharedDirector].winSize;

if (mainMenu != nil) {

[mainMenu removeFromParentAndCleanup:YES];


CCLabelTTF *playScene1Label = [CCLabelTTF labelWithString:@”Level 1″ fontName:@”Motter Tektura” fontSize:45];

playScene1Label.color=ccc3(000, 000, 000);

CCMenuItemLabel *playScene1 = [CCMenuItemLabel itemWithLabel:playScene1Label target:self selector:@selector(playScene:)];

[playScene1 setTag:1];

[playScene1 addChild:stroke z:-1];

CCLabelTTF *playScene2Label = [CCLabelTTF labelWithString:@”Level 2″ fontName:@”Motter Tektura” fontSize:45];

playScene2Label.color=ccc3(000, 000, 000);

CCMenuItemLabel *playScene2 = [CCMenuItemLabel itemWithLabel:playScene2Label target:self selector:@selector(playScene:)];

[playScene2 setTag:2];

[playScene2 addChild:stroke2 z:-1];

CCLabelTTF *playScene3Label = [CCLabelTTF labelWithString:@”Level 3″ fontName:@”Motter Tektura” fontSize:45];

playScene3Label.color=ccc3(000, 000, 000);

CCMenuItemLabel *playScene3 = [CCMenuItemLabel itemWithLabel:playScene3Label target:self selector:@selector(playScene:)];

[playScene3 setTag:3];

[playScene3 addChild:stroke3 z:-1];

CCLabelBMFont *backButtonLabel =

[CCLabelBMFont labelWithString:@”Back”


CCMenuItemLabel *backButton =

[CCMenuItemLabel itemWithLabel:backButtonLabel target:self


sceneSelectMenu = [CCMenu menuWithItems:playScene1,


[sceneSelectMenu alignItemsVerticallyWithPadding:screenSize.height * 0.059f];

[sceneSelectMenu setPosition:ccp(screenSize.width * 2,screenSize.height / 2)];

id moveAction = [CCMoveTo actionWithDuration:0.5f position:ccp(screenSize.width * 0.5f,screenSize.height/2)];

id moveEffect = [CCEaseIn actionWithAction:moveAction rate:1.0f];

[sceneSelectMenu runAction:moveEffect];

[self addChild:sceneSelectMenu z:1 tag:kSceneMenuTagValue];


There are three methods here that are important:

1) playScene which basically receives an item and based on the received item it calls CCDirector to play a scene.

2) displayMainMenu which uses images as buttons to call a second level menu item.  It basically creates menu items and then uses them to populate CCMenu menuWithItems.

3) displaySceneSelection which is called from the displayMainMenu which then takes the user selection and passes it to playScene.

Cocos2d Tips: Animations and image sizing

So you have some art but don’t know how to properly size it for the iPad or iPhone in their 2 versions (retina and non-retina display)! Let’s learn about image sizing and how to use these images in animations for your game objects (player, enemies, power ups or simple eye candy).

Before we even get into creating animations, we need to clear up the sizing issue.  Currently there are 4 screen sizes:

iPhone NonRetina = 480 x320

iPhone Retina = 960 x 640

iPad NonRetina = 1024 x 768

iPad Retina = 2048 x 1536

This means that when creating art for a game, you will go bonkers sizing images for each device.  Backgrounds basically need to cover the whole screen thus they must be the above sizes.  One option is to split the background into parts because some things will scroll and others won’t.  We will take a look at scrolling later on.

Players & images on the other hand will have to be of a certain size.  A typical player image for iPhoneNR will be ~ 1/3 x height = 106.  But in the iPhoneR it must be 212.  On the iPadNR it will have to be 256 and on the iPadR it will be 512 pixels high.  You can get away with iPhoneR being the same size image for iPadNR.  However this is not very useful when you realize we will soon need to get rid of iPadNR assets since it will be phased out.  Phased out because most people switch Apple devices quite frequently.  Anyway, if we don’t consider iPadNR size being phased out, you still have to come up with 3 size images:

106px high

212-256px high

512px high

The problem is that the headache doesn’t stop there.  You must make those images in 2 versions, normal and -hd.  There are programs that help you take an image and automatically get both -hd and non-hd versions of your image but you still have to feed it 3 different sized images.  Cocos2d also helps because you can name those images:





and cocos2d will automatically use the right one wherever needed.

Ok so now you have your images ready.  Now you have to create animations for them.  This means that your outsourced graphic designer must not only create a single image for your main player, but also a few more “frames” to cover that single player’s animation.  Animations can be as complex as you want them because you can animate his jumping, his running, his attacking, his just-standing there etc.  If each animation requires on average 10 “frames” or images…that means you have 10 frames x 4 movement options = 40 frames.  Each of them in 3 sizes and 2 resolutions.  So this can get complicated pretty quick.  But lets just look at how to create a simple animation.

CCAnimation and CCAnimate.  These are CCActions which you can use to animate a sprite.  Basically you do something like this:

CCSprite *animatingSprite = [CCSprite spriteWithFile:@”frame1.png”];

[animatingSprite setPosition:ccp(50,50)];

[self addChild:animatingSprite];

CCAnimation *spriteAnim = [CCAnimation animation];

[spriteAnim addFrameWithFilename:@”frame2.png”];

[spriteAnim addFrameWithFilename:@”frame3.png”];

[spriteAnim addFrameWithFilename:@”frame4.png”];

id spriteAnimationAction = [CCAnimate actionWithDuration:0.5f animation:spriteAnim restoreOriginalFrame:YES];

id repeatSpriteAnimation = [CCRepeatForever actionWithAction:robotAnimationAction];

[animatingSprite runAction:repeatSpriteAnimation];

What we did here is create the sprite as we always do, position it and add it to the layer.  Then we created a CCAnimation and added frames to it.  Finally we used CCAnimate to implement that CCAnimation we created.  However we chained that action with the repeat forever action so we can clearly see the animation.  Sometimes animation frames are too few and too fast to be seen after game launch.

The takeaway here is that you have to create animations for all 3 sizes mentioned above.  This can get cumbersome.  So TexturePacker is very handy for this particular job.  It comes with an option for generating an NR or non-hd version as well as a Retina or -hd version of your images.  This means you still have to come up with the different iPad and iPhone sized images.  Once you name the image as:

frame1.png (which is for iPhone NR ~ 110 px high)

frame1.png (which is for iPadNR and iPhoneRet ~ 250 px high)

frame1.png (which is for iPadRET ~ 500 px high)

This way when you put your images in a Texture Altas file, you can have it generate the -hd versions automatically.  Create an atlas called:



Now when you publish the plist and png files, make sure to click on the AutoSD option in TP.  This will generate:





Now you can simply import ImagesAtlas into your Xcode project and Cocos2d v2.0 will automatically sift through your project and find the corresponding atlas according to the device its running on.

Remember you should create a texture atlas for iPad images and another for iPhone images because if you put them all in one, an iPhone user will have an unnecessarily large atlas being loaded, slowing down his game, which he will never user because he is on the iPhone.