Cocos2d tutorial: Creating a reusable pause layer

This is the first post we are doing for being posted in I really hope you find it useful!

One thing that most, if not all, games have is a pause screen. In all this time developing games with Cocos2d I have seen people asking around the fourms how to do a proper pause screen that can have its elements animated. There are several solutions for this issue, but this is the one i found the easiest to implement and that we have been using for most of our games.

Cocos2d offers a simple method to pause and resume itself, but these methods stop the CCDirector (the class that manages most aspects of a Cocos2d’s app lifetime) from running actions and lower the fps to 5 to conserve battery life.

So, how can we easily get our game to get paused without canceling any running actions or scheduled methods and easily resume leaving the game in the very same state it was before being paused? Here is the answer.

I am going to show you how to create a simple class, PauseLayer, that once it is added to the scene, it pauses the layer we passed as delegate and when this pause layer is removed, it resumes the layer where the game is running.

This is the PauseLayer.h

#import <Foundation/Foundation.h>
#import “cocos2d.h”

@interface PauseLayerProtocol: CCNode


@interface PauseLayer : CCLayerColor {

PauseLayerProtocol * delegate;

@property (nonatomic,assign)PauseLayerProtocol * delegate;

+ (id) layerWithColor:(ccColor4B)color delegate:(PauseLayerProtocol *)_delegate;
– (id) initWithColor:(ccColor4B)c delegate:(PauseLayerProtocol *)_delegate;


And PauseLayer.m

//  PauseLayer.m
//  Pause
//  Created by Pablo Ruiz on 06/06/11.
//  Copyright 2011 PlaySnack. All rights reserved.

#import “PauseLayer.h”

@implementation PauseLayer

@synthesize delegate;

+ (id) layerWithColor:(ccColor4B)color delegate:(id)_delegate
return [[[self alloc] initWithColor:color delegate:_delegate] autorelease];

– (id) initWithColor:(ccColor4B)c delegate:(id)_delegate {
self = [super initWithColor:c];
if (self != nil) {

CGSize wins = [[CCDirector sharedDirector] winSize];

delegate = _delegate;
[self pauseDelegate];

CCSprite * background = [CCSprite spriteWithFile:@”pause_background.png”];

[self addChild:background];

CCMenuItemImage *resume = [CCMenuItemImage itemFromNormalImage:@”pause_btn_resume.png”
CCMenu * menu = [CCMenu menuWithItems:resume,nil];

[menu setPosition:ccp(0,0)];

[resume setPosition:ccp([background boundingBox].size.width/2,[background boundingBox].size.height/2)];

[background addChild:menu];

[background setPosition:ccp(wins.width/2,wins.height/2)];

return self;

if([delegate respondsToSelector:@selector(pauseLayerDidPause)])
[delegate pauseLayerDidPause];
[delegate onExit];
[delegate.parent addChild:self z:10];

-(void)doResume: (id)sender
[delegate onEnter];
if([delegate respondsToSelector:@selector(pauseLayerDidUnpause)])
[delegate pauseLayerDidUnpause];
[self.parent removeChild:self cleanup:YES];

[super dealloc];


This is what is going on in the code. First the PauseLayer is initialized with a color of your choosing and the delegate, which is the layer that we want to pause, generally this would be the layer where the whole game in the current scene is running.  We call the pauseDelegate method which will call the delegate’s pauseLayerDidPause method, that you can implement in your class. You can use this moment to take any actions in your game before pausing.

Then, back in the init method, we add the pause menu’s interface (in this case just a background image and a resume button, but you can add more stuff in there).

When the resume button is pressed, we call the doResume which unpuses the delegate and calls its pauseLayerDidUnpause that if implemented can be used by you to do stuff once the game has been unpaused. Then, the pause layer is removed from its parent.

Since we are not pausing the CCDirector, we can run any action inside this Pause Layer, for example animating its buttons or whatever you need to do.

The magic happens by calling the delegate’s onExit method when pausing it, and then calling the onEnter method when resuming, with just this the layer is frozen and we don’t lose anything that was happening in there. We don’t need to unschedule/re/ schedule selectors or restarting actions.

In order to use this class we just have to go to the game’s layer. Import the PauseLayer.h class and when you intend to pause the game just do:

ccColor4B c ={0,0,0,150};
[PauseLayer layerWithColor:c delegate:self];

That is all. This class has many other uses other than using it as a pause screen. We could create a tutorial screen that pauses the action while it is being shown, for example.

If you have any suggestions to improve it, we are all open to hearing them!

*If you managed to read up to here, please excuse us for the really bad formatting of the code sections! We are trying to find a good WordPress plugin for inserting code. If you know about a good one, please let us know!

Game Programming: Creating infinite seamless scrolling backgrounds.

If you are like any of us in here you must have played Halfbrick’s Monster Dash or the more recent, totally amazing ,Jetpack Joyride.

I can’t avoid playing great games and keep wondering “How the %@*$ did they do that?” and that is what inspired this little tutorial.

What we are going to do is to create a basic logic for creating a scrolling background that uses any amount of different images, loaded and unloaded dynamically when needed.

I don’t claim to know how Halfbrick’s guys did the random, scrolling backgrounds for Jetpack Joyride but this is as closest as I could get while spending little time working on it, and of course there is a lot of room for improvement.

I am going to write down the final code, but there was a lot of trying in the middle which ended in failure for me.

In this example we are scrolling 5 images from top to bottom and looping them infinitely.  The example is made for loading fullscreen images and it runs at a perfect 60 fps with no visible glitches or slowdowns in an iPhone 4 with Retina Display graphics. I’ve yet to try it in older devices or with different sized images.

Here is the code:

//  HelloWorldLayer.h
//  JumpMan
//  Created by Pablo Ruiz on 05/09/11.
//  Copyright InfinixSoft S.R.L. 2011. All rights reserved.

// When you import this file, you import all the cocos2d classes
#import "cocos2d.h"

// HelloWorldLayer
@interface HelloWorldLayer : CCLayer
	int currentBck;
	CCSprite * cachedNode;
	BOOL alreadyLoadedOneNode;
	float timedScale;
	NSMutableArray * backgroundSprites;
	BOOL cachedInitialImage;

// returns a CCScene that contains the HelloWorldLayer as the only child
+(CCScene *) scene;
-(void)cacheTexture:(CCTexture2D *)texturr;
-(void)removeNode:(CCSprite *)n;



The example runs in portrait and it requires for you to have 5 fullscreen (320 x 480) images bck1.png, bck2.png and so on, and their -hd versions too. Just start a new Cocos2d project from the templates and replace the HelloWorldLayer files with the ones provided in here.

Let me explain what the code does:

  1. First, in the init method we initialize the backgroundSprites array which holds our background pieces for updating their positions. Then we set some initial values for the necessary variables we need. After that, we call the loadNode method which we’ll see in a moment. Finally we call the update method which will update the pieces’ positions and manage their unloading.
  2. What the loadNode method does is to tell Cocos2d to load the next texture asynchronously. We do it this way so this new texture is loaded in another thread and we don’t see a hiccup while this is done. Once the texture is loaded, the cacheTexture method will be called.
  3. The cacheTexture method creates the CCsprite from that texture and holds a reference to it so we can add this image right up to the last one when needed.
  4. In the update method we keep moving down the images added to the backgroundSprites array. If one of those images moves past the end of the screen we display the image we had loaded and cached before. Then if that images goes way more past the screen, to the point it is not seen anymore we call the removeNode method.
  5. The removeNode method removes the CCsprite from the layer and removes the texture from the cache to free up memory.

That is all!

Ohh one other thing, the first time this loads, we have the first image right in the place where it should be start SHOWING the next one. That means that we wouldn’t have that second image in the cache loaded, so what we do is to start the scrolling once the second image has been loaded too. This makes the scrolling start half a sec later instead of instantly. This is easily conceivable by adding a “Ready, set, go!” animation or anything that delays the scrolling a little bit!

There is a lot of room for improvement and we are all ears to hearing your suggestions or critics!