Cocos2d – 2D OpenGL for the iPhone made Easy. Part 1.

May 17 2009 Published by under Flash, iPhone, Objective C

Send to Kindle

[NOTE: I checked the cocos2d source out through svn, which I discovered gives you version 0.8. If you download the source, it looks like the latest version available is 0.7.2. I'm not sure how many differences you'll run into, but the first few comments below will show you at least one. But the solution is there as well.]

I’ve been working on iPhone dev obviously, and doing some games. I’ve fooled around with OpenGL a bit, but nothing serious. Been going through Jeff LaMarche’s OpenGL tutorials, which are fantastic. But for a lot of my purposes, I don’t really need the heavy 3D stuff. I really just need something that would do 2D with the power and speed of OpenGL. My last game, Vector Blocks was actually done fully in Cocoa, which I got away with because there’s really only a single object animating at any given time. For any more complex animation, Cocoa would pretty much die. The problem with OpenGL is it’s just so low level, you’d end up writing a ton of code just to get your game character and objects on the screen and moving around, even before you started to think about the actual mechanics of the game.

So I heard mention of cocos2d and went over to Google Code to check it out.

http://code.google.com/p/cocos2d-iphone/

I have to say, I’m pretty impressed. It is just what I was looking for. If you are a Flash / ActionScript developer coming into the iPhone world to make games, this is a dream come true. Basically, it gives you a bunch of objects that encapsulate drawing 2D textures via OpenGL. I shouldn’t have to say this, but cocos2d is NOT a 3D package. There are a few little 3D tricks in there, but for the most part, that “2d” in its name is there for a purpose.

To get started, go to the Google Code link above and download or check out the source. I’ve actually created an XCode template that will give you a cocos2d ready application. I say cocos2d because I didn’t actually include the library in the template. You’ll have to add that to the project yourself. That way I don’t have to worry about updating the template whenever the library changes. You can get the template here:

http://www.bit-101.com/iphone/Cocos2DReadyApplication.zip

Unzip that into your XCode templates directory, which is

/Developer/Platforms/iPhoneOS.platform/Developer/Library/Xcode/Project Templates/Application/

Now you should be able to create a new project and choose a Cocos2D Ready Application.

There are instructions in the project, but the two steps you need to do to start coding are:

1. Add the cocos2d classes to the project.
2. Add the fps_image.png to the Resources group of the project.

For step 1, do NOT add the whole cocos2d folder you downloaded or checked out. Just add the cocos2d subdirectory. Later you might want to add additional packages such as cocoslive or the experimental stuff. But minimally you’ll need the cocos2d dir. For both of these steps, you can choose to either copy the files over into your project, or just access them from wherever you have them stored. It shouldn’t matter to XCode.

For step 2, this png can be found in the Resources/Images folder of the library.

If you’ve gotten this far, you’re ready to start writing some cocos2d. The first thing you need to know about is the Director. This is a well named object. It directs everything that happens. It’s a singleton, so you access it via [Director sharedDirector]. If you go to the main app delegate file in your project you’ll see some commented out code ready for you to implement. This sets up the Director for use.

[[Director sharedDirector] setDeviceOrientation:CCDeviceOrientationLandscapeLeft];
[[Director sharedDirector] attachInWindow:window];

This is pretty obvious. It tells cocos2d that you want to run in landscape mode, and adds the director to the main application window so it can display stuff on the screen.

The next thing you need to know about are Scenes. Scene is another class in the library. You can think of it kind of like states or views in Flex view stack. At any one time you have a single scene running. You can display a scene by calling the runWithScene method of the Director. You can also push a scene onto the Director, which will save the current scene in a stack, or pop a scene off the Director’s stack, which will display the previously pushed stack. Or you can simply replace a scene with a new scene.

So you might have a splash or intro scene, a menu scene, a game scene or maybe multiple level scenes, a high score scene, etc. You just replace or push/pop each scene as needed. Like Flex states, you can use transitions to move between scenes.

So let’s make a scene! Right in the main app delegate class’s applicationDidFinish launching method, just uncomment the code in the template:

- (void)applicationDidFinishLaunching:(UIApplication *)application {
	window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    [window setUserInteractionEnabled:YES];
    [window setMultipleTouchEnabled:YES];

	[[Director sharedDirector] setDeviceOrientation:CCDeviceOrientationLandscapeLeft];
    [[Director sharedDirector] attachInWindow:window];

    [window makeKeyAndVisible];

	Scene *scene = [Scene node];
	[[Director sharedDirector] runWithScene:scene];
}

Don’t forget to add the import statements for cocos2d.h and Scene.h. (These are actually in the template, just uncomment them.)

If you run or debug this now, you’ll see… NOTHING! Obviously, because we haven’t displayed anything. So let’s add something. A background image anyway.

You can easily add an image by creating a Sprite and calling addChild on the Scene. (See, I told you you Flash guys would like this!) First create a 480×320 pixel png file and add it to the Resources folder of your project. I called mine “background.png”. You can see it here:

background

Now change the last few lines of code at the end of the applicationDidFinishLaunching method to look like this:

Scene *scene = [Scene node];
Sprite *background = [Sprite spriteWithFile:@"background.png"];
background.position = ccp(240, 160);
[scene addChild:background];
[[Director sharedDirector] runWithScene:scene];

What we’ve done is create a new Sprite using the background.png image, positioned it in the center of the screen, and added to the scene. A few things about the positioning. You see we are calling a function named “ccp”. This is nothing more than a macro to CGPointMake. Saves you a few key clicks. Also, notice that by default, a sprite’s “registration point” is in its geometric center. So when we set it to the center of the screen, it will be centered in the center, thus filling the whole screen. You can change the registration point via a property called anchor, but we don’t need to just yet.

So run this, and you’ll have a beautiful image like this:

background2

Er… what happened to my nice gradient? Well, you can go to the cocos2d mailing list archives and search “gradient” and you’ll see this is a known issue that has supposedly been fixed, but I sure still see it. What is supposed to fix it is adding this line as the first call to the Director:

[[Director sharedDirector] setPixelFormat:kRGBA8];

Unfortunately, this doesn’t help for me. I still get the ugly banding. Fortunately, I was able to hack into the source code with some hints from the mailing list and at least make a local fix. What I changed is in the Texture2d.m file, around line 193 in the current release. There’s a line that says:

pixelFormat = defaultAlphaPixelFormat;

If you change that to read:

pixelFormat = kTexture2DPixelFormat_RGBA8888;

Your gradients will work just fine. Now, I don’t know what other repercussions this “fix” may have, so use it at your own risk. Or, research it some more, come up with a real fix and submit it to the team.

Disregard that crossed out stuff. I found a better way to handle this here.

Well, that’s about it for now. Next installment, we’ll actually make something move!

Oh, just in case there’s any confusion, here’s the whole applicationDidFinishLaunching method:

- (void)applicationDidFinishLaunching:(UIApplication *)application {
	window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    [window setUserInteractionEnabled:YES];
    [window setMultipleTouchEnabled:YES];

	[[Director sharedDirector] setPixelFormat:kRGBA8];
	[[Director sharedDirector] setDeviceOrientation:CCDeviceOrientationLandscapeLeft];
    [[Director sharedDirector] attachInWindow:window];

    [window makeKeyAndVisible];

	Scene *scene = [Scene node];
	Sprite *background = [Sprite spriteWithFile:@"background.png"];
	background.position = ccp(240, 160);
	[scene addChild:background];
	[[Director sharedDirector] runWithScene:scene];
}
Send to Kindle

34 responses so far. Comments will be closed after post is one year old.

  • Chris Lyons says:

    This is super cool, thanks a ton! Definitely going to help ease the transition from AS3 to objective-c ;-) I’m having an issue with this line:

    [[Director sharedDirector] setDeviceOrientation:CCDeviceOrientationLandscapeLeft];

    error: ‘CCDeviceOrientationLandscapeLeft’ undeclared (first use in this function)

    ended up using this:

    [[Director sharedDirector] setLandscape: YES];

    seems to get the job done. probably a stupid newbie mistake on my part but figured i’d let you know just in case.

  • Hey Keith thanks as always for this great find. I am walking through the steps now and I was getting an error with line

    6.[[Director sharedDirector] setDeviceOrientation:CCDeviceOrientationLandscapeLeft];

    says that it is an undeclared function or whatever so I changed it to the following

    [[Director sharedDirector] setLandscape:YES];

    builds fine and turns the simulator to landscape. Wondering if I may have missed a step or maybe cocoas2d changed the source code or maybe I just missed something in your example.

    Anyway thanks again I just wanted to add commit in case someone else ran into this.

    • kp says:

      Matt, are you sure you have the latest source? Mine gives a warning that setLandscape is deprecated.

  • kp says:

    Just added a note to the top of the post. The svn checkout is for version 0.8, whereas the download is 0.7.2. That’s the difference. So if you are using 0.7.2, yeah, use “setLandscape”.

  • Yeah I figured when I got the error that you where using the svn checkout. So heads up to everyone if setLanscape is deprecated that means it is going away and you should use the svn checkout.

  • John says:

    Having researched unity and a couple of others over the weekend, I was literally going to dive-in with cocos today, you are a mind reader.

    Thanks!

  • I downloaded the latest source and now I am getting an Terminating Due To Uncaught exception if I run it and sometimes it crashes. I am pretty sure that my code is exactly the same other than the version of cocos2d that I am using.

  • kp says:

    does it say where or what the exception is?

  • Dan says:

    Optionally, instead of editing Texture2d.m you can edit the following line in Texture2d.h:

    #define kTexture2DPixelFormat_Default kTexture2DPixelFormat_RGBA4444

    to read

    #define kTexture2DPixelFormat_Default kTexture2DPixelFormat_RGBA8888

  • Mike says:

    I ran across this as well, and was able to fix it by loading the “Default.png” and “Icon.png”, in addition to the “fps_images.png” into my project resources. It seems that the splash screen when Coco2D loads up expect these pngs.

    -Mike

    On May 18th, 2009, Matthew Wallace said:
    I downloaded the latest source and now I am getting an Terminating Due To Uncaught exception if I run it and sometimes it crashes. I am pretty sure that my code is exactly the same other than the version of cocos2d that I am using.

  • [...] Cocos2d – 2D OpenGL for the iPhone made Easy. Part 1. Cocos2D – Part 2 iPhone SDKようのゲームフレームワーク Cocos2d のTips、どこまで続くんだろう期待大。 [...]

  • [...] my first tutorial, I brought up an issue with color banding in gradient pngs used in Sprites in cocos2d. I mentioned [...]

  • Exception Caught issue…. @kp yeah I am an idiot. I started from scratch and forgot to put the fps_images.png back in the project and it was throughing an exception because it could not find the file.

    Not totally used to debugging in xcode just yet :)

  • [...] to Cocos2d iPhone Monocles Studio Intro Collision particle Great site with lots of simple examples Game walkthrough Sapus Tongue [...]

  • Yasuo says:

    I’ve found little change of cocos2d library.

    [[Director sharedDirector] setDeviceOrientation:CCDeviceOrientationLandscapeLeft];

    ↓

    [[Director sharedDirector] setLandscape:YES];

    And, it works fine now.
    Thank you for this tutorial. It helped so much. I’ll continue reading.

  • money says:

    Thanks for your tutorials.
    I make a problem. I only add the cocos2d classes and uncomment #import “cocos2d.h”, #import “Scene.h”.

    It is succeeded when i build it. But it cannot show in iPhone Simulator. It show:

    Error from Debugger: Failed to launch simulated application: Unknown error

  • Julia says:

    I was getting a Terminating Due to Uncaught Exception as well, whether I used 0.8 or 0.7.2. Loading the “Default.png” and “Icon.png” as Mike said, and it helped, but it still did not run. I added “background.png” also, and that fixed it. Although now I have a picture and not a gradient…

  • Benjamin says:

    Hi Keith,

    Greatly appreciate you taking the time to write this up for us! I love your books. Your ActionScript Animation books got me started making Flash games years ago.

    Cheers,
    Ben

  • Quypv says:

    Thanks you very much! your tutorials hepl me full.

  • [...] 個人的にはFlash的に操作できるという点が一番の恩恵だと思っており、最近はXcodeのプロジェクト作成時にcocos2d用テンプレートしか使っていない。テンプレートを使うのであれば例えばCocos2d – 2D OpenGL for the iPhone made Easy. Part 1.に簡素なものがある。自分で作るのであれば【Xcode】設定しておくと便利なカスタマイズいろいろが参考になる。 [...]

  • Ben says:

    Thanks for the great tutorial. I found that I also had to add zlib, as it’s currently a dependency in Cocos2d 8.1.
    This can be done by following this help on Stack Overflow: http://stackoverflow.com/questions/289274/error-when-import-zlib-in-iphone-sdk

    Now to read part 2..

  • Michael says:

    I keep getting “Code Sign error: The identity ‘iPhone Developer’ doesn’t match any valid certificate/private key pair in the default keychain” whenever I build my app. What’s the problem?

  • Rony says:

    Hi,
    I have downloaded cocos2d-iphone-0.99.1 add the subdirectory
    cocos2d to project….but when i built i got 9 error and 4 worning

    Scene.h: No such file or directory
    Director’ undeclared (first use in this function)
    /Volumes/Jobed/cocos2d/CCTexture2D.m:79:24: error: FontManager.h: No such file or directory
    /Volumes/Jobed/cocos2d/CCTexture2D.m:80:35: error: FontLabelStringDrawing.h: No such file or directory
    /Volumes/Jobed/cocos2d/CCTexture2D.m: In function ‘-[CCTexture2D(Text) initWithString:fontName:fontSize:]‘:
    /Volumes/Jobed/cocos2d/CCTexture2D.m:519: error: ‘ZFont’ undeclared (first use in this function)
    /Volumes/Jobed/cocos2d/CCTexture2D.m:519: error: (Each undeclared identifier is reported only once
    /Volumes/Jobed/cocos2d/CCTexture2D.m:519: error: for each function it appears in.)
    /Volumes/Jobed/cocos2d/CCTexture2D.m:519: error: ‘zFont’ undeclared (first use in this function)
    /Volumes/Jobed/cocos2d/CCTexture2D.m:519: error: ‘FontManager’ undeclared (first use in this function)
    /Volumes/Jobed/cocos2d/CCTexture2D.m:521: warning: ‘NSString’ may not respond to ‘-sizeWithZFont:’
    /Volumes/Jobed/cocos2d/CCTexture2D.m:521: warning: (Messages without a matching method signature
    /Volumes/Jobed/cocos2d/CCTexture2D.m:521: warning: will be assumed to return ‘id’ and accept
    /Volumes/Jobed/cocos2d/CCTexture2D.m:521: warning: ‘…’ as arguments.)
    /Volumes/Jobed/cocos2d/CCTexture2D.m:521: error: incompatible types in assignment
    /Volumes/Jobed/cocos2d/CCTexture2D.m: In function ‘-[CCTexture2D(Text) initWithString:dimensions:alignment:fontName:fontSize:]‘:
    /Volumes/Jobed/cocos2d/CCTexture2D.m:567: error: ‘FontManager’ undeclared (first use in this function)
    /Volumes/Jobed/cocos2d/CCTexture2D.m:569: warning: ‘NSString’ may not respond to ‘-drawInRect:withZFont:lineBreakMode:alignment:’

    etc….i don’t know why…i am new can help??

  • [...] I am following the tutorial http://www.bit-101.com/blog/?p=2115.In this tutorial i found a project template and go through it to [...]

  • Galaxy says:

    Its really nice blog for iphone cocos2d beginners. I really appreciate your posts. Thanks for sharing.

  • Jodo Kast says:

    Where is “Scene.h”? I extracted cocos2d, ran their demos OK. Checked your ZIP file above and extracted it, but no Scene.h file.

    I didn’t see above where you create this file, but you mention that it is commented. Where is this? Thank you.

  • Jodo Kast says:

    Above where it indicates “in the main app delegate class” Keith is referring to the file at: Classes\___PROJECTNAME___AppDelegate.m

    I found Import Scene.h there.

  • jumin says:

    [[Director sharedDirector] setPixelFormat:kRGBA8];

    changed to

    EAGLView *glView = [EAGLView viewWithFrame:[window bounds]
    pixelFormat:kEAGLColorFormatRGBA8
    depthFormat:0
    preserveBackbuffer:NO];

  • Jonathan says:

    Hi Keith,

    I downloaded the template, put the cocos2d folder in my “classes” folder, however when I build and run the application I get errors about a missing “FontManager” class along with a few others. I’m essentially getting the same errors as Rony is. Do you have any advice?

    I’m also running Xcode 3.2.5 and building for iOS 4.2 if that helps any.

  • [...] Cocos2d – 2D OpenGL for the iPhone made Easy. Part 1. | BIT-101May 17, 2009 … [NOTE: I checked the cocos2d source out through svn, which I discovered gives you version 0.8. If you download the source, it looks like the … Get the RSS Feed September 8, 2012 at 4:44 am by admin | Category: Uncategorized | [...]