Cocos2D
Writing Your First Cocos2d iPhone Code
by Ben on Mar.04, 2010, under Cocos2D, Code Samples
If you’re like me, you’re probably dying to jump in and start writing some code. We’re about to do just that. By the end of this tutorial, you’ll be able to display a background, graphics and some text. Certainly nothing we really need Cocos2d for, but the few things you’ll learn in this tutorial will form the basis for most of your future code, so it’s worth getting them right at the beginning. If you just want to see the code, jump to the end of the article for the link.
The first thing to do is to boot up Xcode and create a new Cocos2d for iPhone project. If you haven’t installed the templates yet, you can follow the directions here. Create a regular Cocos2d project from the template (not with Chipmunk or Box2d). Once this is done, go into the Classes folder and remove the HelloWorldScene files, we won’t be needing them.
We’re going to have three layers in this project, a background layer, a sprite layer and a text layer. So go ahead and add three new files to your project, and name them BackgroundLayer, SpriteLayer, and TextLayer. We’re also going to need a scene to hold these layers, so create a new file called GameScene. Of course, don’t forget to create the .h files as well. Once you’ve done all that, your project should look something like this:
First we’re going to create our background layer. Open up BackgroundLayer.h, import the cocos2d headers, and make sure the object inherits from CCLayer. You may as well complete these steps in SpriteLayer.h and TextLayer.h as well. Your layer header files should now look like this
-
-
#import "cocos2d.h"
-
-
@interface BackgroundLayer : CCLayer {
-
-
}
-
-
@end
-
We’re only going to write one method in the implementation files for now, which will be the init method. I’ll show the code first, and then we can go through it:
-
-
#import "BackgroundLayer.h"
-
-
@implementation BackgroundLayer
-
-
- (id) init
-
{
-
self = [super init];
-
if (self != nil) {
-
//load image file
-
CCSprite *background = [CCSprite spriteWithFile:@"background.png"];
-
//get the current screen dimensions
-
CGSize size = [[CCDirector sharedDirector] winSize];
-
//place the image in the center of the screen
-
background.position = ccp(size.width/2, size.height/2);
-
//add the sprite object to the layer
-
[self addChild:background];
-
}
-
return self;
-
}
-
-
@end
The code should be fairly self explanatory. Basically we are just loading an image file and placing it in the center of the layer. The only thing that might not be familiar is “ccp”, with is a Cocos2d method for creating a point. If you need a background image, you can find one here. Make sure you include the file in your project as you normally would.
Next we’ll implement the SpriteLayer. This is going to be very similar to the BackgroundLayer, except this time we will place the image off to the left of the screen. The X and Y axes in Cocos2d start from the bottom left corner, not the top left, where as sprites work from the center of the image. So by placing the image at position 150, 150, we are effectively saying “place the center of the image 150 pixels up from the bottom of the screen, and 150 pixels across from the left”. Once we’ve got the code up and running, change the position of the image a few times to get a better understanding of this. If you can’t manage to find your own image, here is the one we used.
-
-
#import "SpriteLayer.h"
-
-
@implementation SpriteLayer
-
-
- (id) init
-
{
-
self = [super init];
-
if (self != nil) {
-
//load image file
-
CCSprite *robot = [CCSprite spriteWithFile:@"robot.png"];
-
//place the image to the left of the screen
-
CGSize size = [[CCDirector sharedDirector] winSize];
-
robot.position = ccp(150, size.height/2);
-
//add the sprite object to the layer
-
[self addChild:robot];
-
}
-
return self;
-
}
-
-
@end
-
Next, we’ll create the last layer. Rather than showing an image this layer will display some text. If you’ve used UILabels at all, which I’m sure you have, then CCLabels will be look quite familiar. Here’s the implementation for the TextLayer:
-
-
#import "TextLayer.h"
-
-
@implementation TextLayer
-
-
- (id) init
-
{
-
self = [super init];
-
if (self != nil) {
-
CCLabel* myLabel = [CCLabel labelWithString:@"Dance Like A Robot" dimensions:CGSizeMake(100,100) alignment:UITextAlignmentCenter fontName:@"Arial" fontSize:30];
-
CGSize size = [[CCDirector sharedDirector] winSize];
-
myLabel.position = ccp(360, size.height/2);
-
[self addChild:myLabel];
-
}
-
return self;
-
}
-
-
@end
-
Now that we’ve created our three layers, we can tie them together in our scene class. This is a fairly simple matter of adding each layer to the scene. Here’s the implementation, don’t forget to also import the cocos2d header files and inherit from the CCScene class in the GameScene.h file.
-
-
#import "cocos2d.h"
-
-
@interface GameScene : CCScene {
-
-
}
-
-
+(id)scene;
-
-
@end
-
-
-
#import "GameScene.h"
-
#import "BackgroundLayer.h"
-
#import "SpriteLayer.h"
-
#import "TextLayer.h"
-
-
@implementation GameScene
-
-
+(id)scene {
-
// ’scene’ is an autorelease object.
-
CCScene *scene = [CCScene node];
-
-
// ‘layer’ is an autorelease object.
-
BackgroundLayer *backgroundLayer = [BackgroundLayer node];
-
SpriteLayer *spriteLayer = [SpriteLayer node];
-
TextLayer *textLayer = [TextLayer node];
-
-
// add layers as a children of the scene
-
[scene addChild:backgroundLayer];
-
[scene addChild:spriteLayer];
-
[scene addChild:textLayer];
-
-
// return the scene
-
return scene;
-
}
-
-
@end
-
As you can see, we simply create each of the layers and then add them as children to the scene. The order you add them in is important, so if you add the background last you won’t see the other two layers. One other thing you might be unsure of is the call to “node” when creating the layers. You can pretty much call “node” on any Cocos2d object and it will create a new instance of it. So if you call “node” on a CCLayer, it creates a new CCLayer. If you call “node” on a CCSprite, it returns a new CCSprite. Think of it as a bit like calling alloc/init on your normal Objective C objects.
Finally, to get everything up and running we need to modify the app delegate a bit. Change the imports so that we’re importing “GameScene.h” rather than “HelloWorldScene.h”, and then change the last line of the applicationDidFinishLaunching method accordingly. Note that we are telling the CCDirector that we want to start running with the GameScene. Later on we’ll learn how to set up a menu, and call different scenes at different times.
-
-
[[CCDirector sharedDirector] runWithScene: [GameScene scene]];
-
You should now be able to build and run to see your beautiful creation. Once you’re done, play around with the positioning numbers a bit, or add some new sprites. You should now have the very basics of starting your Cocos2d project covered.
For those who can’t get things working, here’s a copy of the project that includes everything we did in this tutorial.
Installing the Cocos2d iPhone Templates
by Ben on Feb.25, 2010, under Cocos2D
To get started writing Cocos2D code, the first thing you’ll want to do is install the Xcode templates. The templates are a great starting point for any Cocos2D project, particularly if you want to create projects using the Chipmunk or Box2d physics libraries.
First of all, make sure you have the latest release downloaded and stored somewhere suitable – I recommend in your iPhone projects folder. For reasons mentioned here, I recommend the latest unstable release (at least until v1.0 comes out).
To install the templates, you’ll want to open up the Terminal. If you’re not sure how to open up the Terminal, Spotlight is your friend. Just hit Command-Space, and type in Terminal. This is a great way to open apps or documents you don’t have quick access to, or are not sure where they are stored.

So, once the Terminal is open, navigate to where the Cocos2d project is stored. When you are inside the folder, all you need to run is
-
./install_template.sh
Once the script has finished executing, open up Xcode and start a new project. You should now have three new templates in there to get started with. I suggest you make a new project for each type, and run them to see what happens. It’s a good idea to have a quick look around in the code as well to see how things work.
If for some reason you want to remove the templates, or remove an older version of the templates, you can find out where they are stored by viewing the “install_template.sh” file. Open it up in TextEdit, and have a look at the first few lines of the script – most likely they will mention this directory: “/Developer/Platforms/iPhoneOS.platform/Developer/Library/Xcode/Project Templates/Application/”. Navigate to that folder from the Finder, and remove any templates you no longer want.
Key Classes in Cocos2d
by Ben on Feb.15, 2010, under Cocos2D
There are a few classes in Cocos2d that you are likely to come across over and over again. Since you’ll be seeing them so frequently, getting to know them right away seems like a good place to start.
CCDirector – The CCDirector class is in charge of running the show. If you want to pause your game for some reason (eg. a phone call comes in), it’s as simple as telling the CCDirector to pause – and another one line call will allow you to resume your game exactly where it left off.
CCScene – In a typical game, as well as the gameplay itself, there are also high scores to view, settings to change, a tutorial to read, and so on. Cocos2D handles all the movements between these different parts of your game by representing each as a CCScene. So, you might have a GameScene, a HighScoresScene, a SettingsScene, and a TutorialScene. Cocos2D then allows you to transition between these scenes at the appropriate time with ease.
CCLayer – Each scene is usually made up of one or more layers. If we are in the GameScene, then you might have a BackgroundLayer which simply displays the background, a PlayerLayer which holds your spaceship or character, and an EnemiesLayer, which holds all of the things you’re trying to kill. This allows for a good object orientated design, and allows each layer to handle input, collisions, and so on, as appropriate.
CCSprite – A CCSprite represents a graphic object. This is what you’ll use to represent your game characters, weapons, enemies, and so on. CCSprite offers a very simple means to load in graphics, move them around and do all other sorts of things to them.
CCLabel – As you might expect, this class allows you to render text on screen.
CCNode – The CCNode class is the simplest object type in the game, which everything is derived from. If it’s drawn on screen, moves around, or contains things that are drawn on screen, then it’s a type of CCNode. CCScene is a CCNode, CCLayer is a CCNode, etc. Think of CCNode as bit like the NSObject of Cocos2d.
One thing to note is that v0.9 of Cocos2d introduced the CC namespace. This means that a lot of the examples you find on the net no longer work, but it’s a fairly simple fix – just prefix any of the Cocos2d class references with “CC”. If you’re after a little bit more on the key classes, have a read of this great introduction. Just remember that the article is a bit outdated, and doesn’t include the CC namespace.
Running the Cocos2d Demos
by Ben on Feb.06, 2010, under Cocos2D
The Cocos2d for iPhone Xcode project comes with a number of demos, which are useful both for seeing visually what the engine is capable of, and for digging into the code to see how things are done.
To start, download the latest version from the official Cocos2d for iPhone website. There are a few options for which package to download, but I recommend you get the latest Unstable Version. As Cocos2d is still in pre-release the API is in somewhat of a state of flux, and it often changes some between versions. In my experience the unstable versions have actually been perfectly stable, and have the benefit of including all the latest API changes, meaning you won’t need to mess around making changes to your code later on.
If you open up the downloaded archive, you’ll see an Xcode project inside:
As you can see, I’m currently running Cocos2d v0.99.0-rc – in other words the release candidate for v1.0. Open up the Xcode project and do a Build as a sanity check to make sure everything is ok. You might get some Warnings, but these can be safely ignored.
To run the demos, you’ll probably need to make a small change to your Xcode settings. Go to the View menu, and choose Customize Toolbar. From here, you want to drag both the Active Target and the Active Executable drop downs on to your toolbar, like so:
![]()
You’ll then need to select the same thing for both the Active Target and the Active Executable, as in the image above. You might also need to change the Overview drop down so that the code runs on a version of the Simulator (or your Device, if you prefer).
At the moment there are about 40 demos you can run, so work your way through them to get a feel for the library.
Introduction to Cocos2D for iPhone
by Ben on Feb.04, 2010, under Cocos2D
Now that we’ve decided upon Cocos2D for our game engine, let’s take a look into what the engine offers. Before we get too much further in though, I’d like to recommend that if you are brand new to the iPhone platform and/or Xcode, I would highly advise that you do a little catch up reading. One of the best ways to do this is to read Beginning iPhone Development. This really is one of the best books around on how to get started developing on the iPhone, and gives a good coverage of what you can do with the platform.
Now that that’s out of the way, we can a look at what Cocos2D has to offer. If you take a look at the official Cocos2D for iPhone website, there is a quick summary in the About section of the main engine features. Let’s go over a few of them:
- Scene management – just about all games have different screens apart from the main game. These might be high scores, settings, different levels, and so on. Cocos2D lets you set these up easily, and transition between them with a number of (sometimes cheesy) effects.
- Sprites – a sprite is pretty much the technical name for a graphic or image. If your game includes any sort of graphics, generally they will be handled by the Sprite class in Cocos2D in a memory efficient manner.
- Actions – Cocos2D allows you to run all sorts of actions on your sprites, such as movement, rotation and scaling.
- Physics engine – Cocos2D integrates with two well established physics engines, Box2D and Chipmunk. Both engines allow you to easily implement complex physics interactions between objects and the game environment.
- Menus – setting up your menus and controlling the flow between the different parts of your game couldn’t be much easier.
Naturally, Cocos2D offers many other things, but the points above are probably the main features you’ll be using, at least while we get started. While you’re looking at the About page on the official site, you might as well check out the videos as well. These show off some of the different effects that the engine is capable of.



