I n this tutorial i’m going to show you how to create a simple but very comprehensive for beginners game in Cocos2D for the iPhone. This first part is going to focus on the Cocos2D basics and how to create menus, scenes and transitions between them.
Before you go on:
You need to have installed the iPhone SDK and the Cocos2D framework for iPhone. If you don’t know what i’m talking about or you know but you don’t have either of them installed you should check http://www.oscarvgg.com/installing-cocos2d-for-iphone/ before reading this tutorial.
I’ll assume that you have basic knowledge of programming and a minimal knowledge of the Objective-C language (by minimal i mean creating variables, methods and call them, classes, instance objects, etc.) and use of Xcode. This tutorial is focused in Cocos2D only.
I´ll also assume that you understand the basic concepts of the Cocos2D framework like what is a “scene”, the “director”, a “layer” and a “sprite”. If you don´t, then go to http://www.cocos2d-iphone.org/wiki/doku.php/prog_guide:basic_concepts, there you´ll find all the information you need to understand how Cocos2D works.
Creating a new Cocos2D project.
Open Xcode and click on File->New Proyect. Then select “User Templates” in the left sidebar of the “New Project Window” and double click “Cocos2d Aplication”.

Give a name to your project. I’m going to call mine: “FirstGame”.
Understanding the App Delegate.
In “Groups and Files”, double click on classes to expand it and then click on [Your game Name]AppDelegate.m, mine is FirstGameAppDelegate.m.

This file is the most important of your app, it is responsible for managing all your application behaviors for all the different states it can have, as all it’s methods are listeners for Application Events. For Example, if your app goes to background, the AppDelegate automatically runs the method applicationDidEnterBackground.
The first method you’ll find in the implementation file of the FirstGameAppDelegate class is applicationDidFinishLaunching. This method, as it’s name says it, runs when you launch your app. At the beginning it creates an instance of a the director, the one that handles everything that has to do with the scenes.
In the next line it sets the initial orientation of the screen. By default it is set to landscape-left with kCCDeviceOrientationLandscapeLeft, you can change it to landscape-right with kCCDeviceOrientationLandscapeRight, to portrait with kCCDeviceOrientationPortrait or even to portrait-upside down with CCDeviceOrientationPortraitUpsideDown. For now i’m going to leave it like it is.
The last line of the method is [[CCDirector sharedDirector] runWithScene: [HelloWorld scene]];, it tells the director with what scene is the application going to start, in this case it is “HelloWorld”.

Creating the Gameplay layer.
Click on File->New File… click on “User Templates”, “Cocos2D 0.99.4” and double click CCNode Class.

I’ll call my new class “GamePlay”, you can give it the name you want (just make sure it has the .m extension) and click Finish.

Now open GamePlay.h, make it extend CCLayer and add the scene method. It should look like this:
1 2 3 4 5 6 | #import Foundation/Foundation.h; #import "cocos2d.h"; @interface GamePlay : CCLayer { } +(id) scene; @end |
In GamePlay.m, add the implementation of the scene method and an empty init method, like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | +(id) scene { // 'scene' is an autorelease object. CCScene *scene = [CCScene node]; // 'layer' is an autorelease object. GamePlay *layer = [GamePlay node]; // add layer as a child to scene [scene addChild: layer]; // return the scene return scene; } -(id) init { if( (self=[super init] )) { } return self; } |
We just created the scene where our gameplay is going to be but we are not going to add it for now, you’ve got to wait for part 2.
Creating a menu.
Open HelloWorldScene.m and find the init method. Erase everything within “if( (self=[super init] ))” and let’s create a menu in it’s place. If you are a little lost, don’t worry, it is normal. HelloWord is the first scene that the user is going to see when the app starts, this menu comes to be the main menu of the game.
First we have to set the font, type:
1 | [CCMenuItemFont setFontName:@"Marker Felt"]; |
I chose “Marker Felt”, you can use other font that you like.
Next we set the size, i want it to be 35.
1 | [CCMenuItemFont setFontSize:35]; |
Now we are going to create a menu item. This item is what is going send us to the gameplay when selected.
1 2 3 | CCMenuItem *Play = [CCMenuItemFont itemFromString:@"PLAY" target:self selector:@selector(goToGameplay:)]; |
I called it Play, but it is just the name of the object, in the screen it is going to say “PLAY” because i’m passing itemFromString:@”Play”. We are targeting self and we are saying that the method that is going to be executed when the user tab “Play” is “goToGameplay” as selector:@selector(goToGameplay:)], but we haven’t created it yet, we can worry about that later, for now let’s finish with the menu.
By now we have just defined a menu item, not the menu itself. So we have to create a ccmenu object and add the Play item to it:
1 | CCMenu *menu = [CCMenu menuWithItems: Play, nil]; |
You can add as many items as you want but never forget to add nil at the end of the list.
Let’s position the menu to the center of the screen
1 | menu.position = ccp(240, 160); |
(240, 160) is the center of the screen of every iPhone-iPod touch, even those who has retina display. Cocos2D works with points, not pixels, points. If you are using an iPhone-iPod touch previous to iPhone 4, a point is equivalent to one pixel, if not, you are using a devise with retina display, in that case a point is equivalent to four pixels, so the screen of every iPhone-iPod touch is 480×320 points, you don’t have to worry about the resolution of the screen, Cocos2D takes care of that. (Retina display resolution is 960×640 and it has the same 3.5-inch (diagonal) screen as earlier iPhones).
If you are working with an iPad, your resolution is 1024×768 and the center of your screen is 512×384 pixels so you have to position the menu at cpp(512, 384).
And finally we say the scene to add the menu to itself.
1 | [self addChild:menu]; |
Your init method should look like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | -(id) init { // always call "super" init // Apple recommends to re-assign "self" with the "super" return value if( (self=[super init] )) { [CCMenuItemFont setFontName:@"Marker Felt"]; [CCMenuItemFont setFontSize:35]; CCMenuItem *Play = [CCMenuItemFont itemFromString:@"Play" target:self selector:@selector(play:)]; menu.position = ccp(240, 160); [menu alignItemsVerticallyWithPadding:10]; [self addChild:menu]; } return self; } |
Switching to Gameplay with transition:
In order to switch to the gameplay scene you have to create the goToGameplay method. But before that, don’t forget to import the gameplay scene, if you do, Xcode is not going to know what is gameplay and is going to insult you. You just have to type #import “GamePlay.h” at the beginning of the code.
Ok, type:
1 2 | -(void) play: (id) sender { } |
Now we tell the director to replace the scene with this line of code:
1 2 3 4 5 | [[CCDirector sharedDirector] replaceScene:[CCFadeTransition transitionWithDuration:1 scene:[GamePlay node] ] ]; |
We are saying: “Use the transition CCFadeTransition lasting one second to replace this scene with Gameplay scene”, easy as pie.
You can use other transitions like CCShrinkGrowTransition or CCPageTurnTransition among others that i don’t remember. To learn more about transitions types you can always check the API documents.
After the last step, your HelloWorldScene.m file should look like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 | #import "HelloWorldScene.h" #import "GamePlay.h" // HelloWorld implementation @implementation HelloWorld +(id) scene { // 'scene' is an autorelease object. CCScene *scene = [CCScene node]; // 'layer' is an autorelease object. HelloWorld *layer = [HelloWorld node]; // add layer as a child to scene [scene addChild: layer]; // return the scene return scene; } // on "init" you need to initialize your instance -(id) init { // always call "super" init // Apple recommends to re-assign "self" with the "super" return value if( (self=[super init] )) { [CCMenuItemFont setFontName:@"Marker Felt"]; [CCMenuItemFont setFontSize:35]; CCMenuItem *Play = [CCMenuItemFont itemFromString:@"Play" target:self selector:@selector(goToGameplay:)]; CCMenu *menu = [CCMenu menuWithItems: Play, nil]; menu.position = ccp(240, 160); [menu alignItemsVerticallyWithPadding:10]; [self addChild:menu]; } return self; } -(void) goToGameplay: (id) sender { [[CCDirector sharedDirector] replaceScene:[CCTransitionFade transitionWithDuration:1 scene:[GamePlay node] ]]; } // on "dealloc" you need to release all your retained objects - (void) dealloc { // in case you have something to dealloc, do it in this method // in this particular example nothing needs to be released. // cocos2d will automatically release all the children (Label) // don't forget to call "super dealloc" [super dealloc]; } @end |
Testing the app:
Click build and run.

If you did everything well your iphone simulator should open and display the menu that we’ve created.

When you click Play, it should take you to our empty gameplay scene, it is a black square because we haven’t added anything to it yet.

Conclusion:
In this tutorial we have learned how to create a Cocos2D app from a template, we understood how the director works and how to create a scene, a menu and how to add transitions between scenes.
In the next part i will show you how to create a pause scene for the gameplay, how to add sprites and backgrounds to scenes.
Until then.
Go forward: Your first Game in Cocos2D – Part 2: Sprites and More Transitions
Or if you feel ready: Your first Game in Cocos2D – Part 3: The Gameplay





Hi Oscar,
Thank you for this tutorial, when do you think the next one will be up?
-Peter
i believe this weekend i’ll Finish writing it…
great to hear, I am aching to get on with it
Thanks for the simple tut. Can’t wait to see the next!
I want to thank you for your efforts you have made in making this blog. I am hoping the same good work from you in the future as well. In fact your great writing abilities has inspired me to start my own blog. Really the blogging is spreading its wings rapidly. Your content is a fine example of it.
Thanks for your comments. It is always good to know that your work is inspiring other people.
Dude, I absolutely loved reading this blogpost. You have convinced me to subscribe to your blog, but where can I find the RSS feed?
In the header and the footer you’ll find 4 cans, each one of the represents a way to follow this blog.
Here are the links anyway:
RSS feed: http://www.oscarvgg.com/?feed=rss
Facebook: http://www.facebook.com/pages/OscarVGG/149669261739306
Twitter: http://www.twitter.com/oscarvgg
eMail: http://feedburner.google.com/fb/a/mailverify?uri=theprogrammerlifestyle&loc=en_US
Thanks for reading.
Oscar.
Thank you for the great tutorial. It is the best explanation if some of these concepts Ive seen yet.
I would love to see something from you talking about accessing and moving layers vs the camera. This is something I am having a hard time getting to work correctly.
Hello – I must say, I’m impressed with your site. I had no trouble navigating through all the tabs and information was very easy to access. I found what I wanted in no time at all. Pretty awesome. Would appreciate it if you add forums or something, it would be a perfect way for your clients to interact. Great job!
Thanks for your good comments, I appreciate that people value my work.
I’m actually working in a forum for the site right know, i don’t know when it’s going to be finished, i’m taking my time because i wan’t it to look good.
I came across this website trying to find some answers to my question about summer gardening. This blog wasn’t exactly what I was trying to find, it did manage to help answer some of my more unrelated questions that I wasn’t able to find an answer to some time ago. I’m impressed by your viewpoint as well.
Reading this reminds me of my old room mate. That guy was one of the smartest characters I know, but he was a little beatnik for my tastes though. Anyways I liked reading this, thanks. Will give me something to talk about when I see him.
This is the first blog I read on my new Ipad. I’ll be back.
Thanks, do you happen to have a facebook i can follow up? really interested.cya
Sure:
Facebook: http://www.facebook.com/pages/OscarVGG/149669261739306
Also:
Feed: http://www.oscarvgg.com/?feed=rss
Twitter: http://www.twitter.com/oscarvgg
Mail: http://feedburner.google.com/fb/a/mailverify?uri=theprogrammerlifestyle&loc=en_US
Thanks For Your post, was added to my bookmarks.
Kudos from one brainiac to another.
Very nice post.
I actually think so too:P I have been searching around the web for some time today, and its really hard to find something good to read on blogs=P Maybe thats because there are too much of those around =) But this website actually keeps catching my attention=) Great posts, and kawai design ^__^. Ill be sure to give it more time now =]
Thanks for this page. I’ve read it in the metro with my phone and found it very interesting.
Many thanks very much for the info. I have been looking for this for a while with Bing and it has been a true undertaking.
Hi, Thanks for the awesome post you have! Im following your blog now
Great wordpress blog here.. It’s hard to find quality writing like yours these days. I really appreciate people like you! take care and see you soon
This is a great knowledge. Thank you very much for sharing those post. I will absolutely check it out.
I love the way you write and also the theme on your blog. Did you code this yourself or was it done by a professional? I’m very very impressed.
Yes, it was done by a professional: me. I Hope this is not spam, sorry if your intensions are real.
Thanks anyway!
Freakin nice blog.
Aw, this was a really quality post. In theory I’d like to write like this too – taking time and real effort to make a good article… but what can I say… I procrastinate alot and never seem to get something done.
man please more more more of this stuff
shares utilize a excellent web-site decent Gives thanks for the working hard to guide me
Maybe the top post I have read ever!!!
Jodi
I tried this tutorial, followed the instructions and found that the game autoquits when it is run. After analyzing the code and tutorial I found that there was a part of this tutorial which is a bit misleading.
The part is:
at the Switching to Gameplay with transition part of the tutorial we are told to type :
-(void) play: (id) sender {
}
It should be :
-(void) goToGameplay: (id) sender {
}
Good thing there’s a “how the code should look like part” so I could compare my code. LOL
Good tutorial BTW Thumbs up
Thanks for your correction, sometimes i modify the code in Xcode but I forget to change the text of the tutorial… :S
Hi,
Thanks for taking the time to explain the basics of getting Cocos up and running, much appreciated. Just a quick note, on the section ‘Creating a Menu’ and the bottom, where you show the code listing entitled ‘Your init method should look like this:’ you don’t declare the menu variable. Nothing major, but made me chuckle a little, as you did include it in the breakdown above it. Anyway, thanks again for a very helpful article.
Can you please upload the source code for this
Hi Oscar,
This tutorial was very easy to follow. The build succeeded but then
-Got an error message about Base SDK not available (?) something in the (Active Executable Menu)
-I changed Xcode Project Settings (Base SDK for All Configurations) to iOS 4.0 simulator
and Project Format: Xcode 3.2 compatible
The app launched in iPhone simulator but it Show the Cocos logo (full screen) then switched to landscape view and displayed only the cocos icon.
When I selected iOS Simulator 3.2 and build/run, The iPad simulator opened and did the same thing.
Any idea what I am doing wrong here?
*** Terminating app due to uncaught exception ‘NSInvalidArgumentException’, reason: ‘+[NSInvocation invocationWithMethodSignature:]: method signature argument cannot be nil’
Something tells me that’s not supposed to happen. After the first failure, I copied your code exactly, fixed the spacing (which doesn’t actually matter in C), and it gave me that again. And again.
Pay me no mind. I entered
- (void)play:(id)sender {
instead of
- (void)goToGameplay:(id)sender {
No idea how I did that, but there you go.
When I tried to build the code I got an error on CCFadeTransition with a litte looking found that it should have been CCTransitionFade
Help… Im getting a CCFadeTransition Undeclared error…
Version issue. The answer is posted later
Hi,
Excellent tutorial so far. I just noticed an error in this line:
[[CCDirector sharedDirector] replaceScene:[CCFadeTransition transitionWithDuration:1 scene:[GamePlay node]]];
CCFadeTransition should be CCTransitionFade. Just a small mistake.
Going to continue with the tutorial. I’ll let you know if there are any more errors.
Is a version issue
Great tutorial, but stil i got an error
“/Documents/FirstGame/Classes/HelloWorldScene.m:61: error: ‘CCFadeTransition’ undeclared (first use in this function)”
found 5 errors in the code when i try to run simulator after 1st step…
in your tut for example, theres differences between what you’re putting down step by step to add between “if( (self=[super init] ))” in HelloWorldScene.m and your example of what it should look like, also i don’t fully know what i’m doin just yet, so if you’d include the source code for your tut series it would be really awesome for all us ubber noobs… respect!
I’ll think about it… I believe you learn more when you try to fix the problem yourself instead of using already written code… But definitively going to think about it!
First thanks for posting this it’s super helpful. However, I am receiving this error and I’m not sure how to get around it. Where should I declare ‘CCFadeTransition’?
…/HelloWorldScene.m:64: error: ‘CCFadeTransition’ undeclared (first use in this function)
I found the problem. I should have been calling CCTransitionFade rather then CCFadeTransition. That seems to have fixed it.
hey =D your blog is great.
I had a little trouble to compile this =C
it sends the error: ‘CCFadeTransition’ undeclared
I tried using the other that you menction but it always says the same, could you help me?
When I build and run I get 1 error: CCFadeTransition undeclared (first use in this function). Obviously it needs to be used somewhere else in the function, but I am a noob and am not sure how to solve this. Help would be appreciated!
They changed it to CCTransitionFade in the new version…
Wonderful article post on the blog bro. This particular is just a tremendously nicely structured blog post, just the data I was looking just for. Thank you.
Hi. I like your website but i can tell it probably isn’t getting much traffic? If you want to help imrpove that check this website out, he has a short video that i really suggest you watch. Commission Crusher P.S this isn’t my website and i’m not spamming your blog, i don’t care if you delete this comment. I am only trying to help you improve your site.
Oscar, thank you very much for posting these tutorials!
I was able to get this one working with Xcode 4 and the RC of Cocos2d (cocos2d-iphone-1.0.0-rc.tar.gz) with just a few changes:
1. In my project template I didn’t have HelloWorldScene.m or .h so I used HelloWorldLayer.m and .h
2. I had to manually create the GamePlay.m and .h files; the Cocos2d file templates aren’t ready yet for Xcode 4. Perhaps I missed them but if you could post the source code for the files in the tutorial that would likely help many people.
3. CCFadeTransition is now CCTransitionFade
Great tutorial but:
[[CCDirector sharedDirector] replaceScene:[CCFadeTransition transitionWithDuration:1 scene:[GamePlay node]]];
should be:
[[CCDirector sharedDirector] replaceScene:[CCTransitionFade transitionWithDuration:1 scene:[GamePlay node]]];
ip pbx system to curl until flights to new jersey.
Hi Oscar,
One minor correction in goToGameplay:
[[CCDirector sharedDirector] replaceScene:[CCFadeTransition transitionWithDuration:1 scene:[GamePlay node]]];
should be:
[[CCDirector sharedDirector] replaceScene:[CCTransitionFade transitionWithDuration:1 scene:[GamePlay node]]];
Yes, it changed in the new version. i’ll update it as soon as possible
CCFadeTransition has been changed to CCTransitionFade in the latest version of cocos2d
Thanks for clarification. Stay around, we may need you!
Hey! I know this is somewhat off topic but I was wondering if you knew where I could locate a captcha plugin for my comment form? I’m using the same blog platform as yours and I’m having trouble finding one? Thanks a lot!
It’s in the wordpress plugins list. You can find it in the Plugins section of the admin panel.
Incredibly maintained and respected net directory. Rid entry and moderation. Augment your relation and you inclination feel the power of our directory. setakowa.
The code compiles (with the updated CCTransitionFade reference) in Xcode 3.2.6 and cocos2d 0.99.5, but it crashes before the “Play” menu displays. I am trying to figure it out but am not very familiar with the debugger. Thank you for the tutorial! Hopefully I can figure it out as I familiarize myself with Objective C and cocos2d.
Hello Oscar, I love your tutorial, but I keep getting errors and I have no idea what I’m doing wrong. The errors are:
In GamePlay.m:
LLVM GCC Error: no super class declared in @interface for ‘GamePlay’
Sematic Issue: no super class declared in @interface for ‘GamePlay’
Cannot find interface declaration for ‘GamePlay’
Warning: ‘GamePlay’ may not respond to ‘-addChild:z:’
In PauseScene.m:
Parse Issue: Expected identifier
Warning: ‘CCTransitionFade’ may no respond to ‘+transitionWithDuration
-Please Help, I have no idea what I’m doing!
You may have forgotten to extend or inherit form CCLayer or something like that…
Let me know if you could fix it.
I’m sorry, but could you elaborate some more? I don’t know where to put such things.