iPhone
Hello Cocos2d
April 8, 2009
0

This is a guide to create a Hello World application for cocos2d.  If you have not installed and compiled the Cocos2d successfully, then follow the previous guide here.

Note: this guide is written for cocos2d version 0.71. If you are using 0.73 or later and are having issues, check the following post:
https://permadi.com/blog/2010/03/cocos2d-compiling-hint/
https://permadi.com/blog/2010/03/cocos2d-for-iphone-migrating-0-71-to-0-73/

Step1

Create a new project, using File->New Project menu.

Step2

Select Window-Based Application.

hellococos2dnewproject

We did not select View-Based because we will not be needing an UIView in this example.  We do not select Utility Application because this will not be an utility.  We do not select Navigation Based or Tab-Bar because our example will only have one section.  Finally, we do not select the OpenGS EL because cocos2d will handle the OpenGL stuff and if you select that Open GL template, you’ll get too many extraneous stuff.

Name the project HelloCocos.

Step3

The project should look something like below.  Notice the project wizard has created several files:  HelloCocosAppDelegate.h, HelloCocosAppDelegate.m, Info.plist, main.m, MainWindow.xib.

HelloCocosAppDelegate.m is the application class file.  This class is the one that we will be working on for this example.  hellococos2dprojscreen

If you do a Build and Go now, you will get a blank application (a white screen).  Try it now, using Build->Build and Run menu.

Step3

Open HelloCocosAppDelegate.m, add #import “cocos2d.h” (see the code snippet below).  This enables the cocos2d classes into our code.

Step4

Add the following into the applicationDidFinishLaunching method:

 

- (void) applicationDidFinishLaunching:(UIApplication*)application
{
	// Init the window
	window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];

	// attach cocos2d to a window
	[[Director sharedDirector] attachInView:window];

	Scene *scene = [Scene node];

	Layer* layer=[Layer node];

	CGSize s = [[Director sharedDirector] winSize];
	Label* label = [Label labelWithString:@"Hello cocos2d" fontName:@"Arial" fontSize:32];
	[layer addChild: label];
	[label setPosition: cpv(s.width/2, s.height-50)];

	[scene addChild: layer z:0];

	[window makeKeyAndVisible];

	[[Director sharedDirector] runWithScene: scene];
}

 

What the code does is creating a Scene object (in the line Scene* scene=[Scene node].  It then creates a Layer object and adds a Label into the Layer.  We draw the text “Hello cocos2d” into a Label that we put into the Layer.  Finally, we add the Layer into the Scene.

So the hierarchy is as follows:

Window contains Scene; Scene contains Layer; Layer contains Label.

The sharedDirector is Cocos2 global controller, which handles the display. Currently it doesn’t do much.

That’s it for the coding portion.  Note: in a real app, you should always delete the objects you created, such as the Scene and Layer objects we created.

Step5

If you do a Build now, you will probably get a bunch of errors like this:

Line Location HelloCocosAppDelegate.m:10: error: cocos2d.h: No such file or directory
Line Location HelloCocosAppDelegate.m:22: error: ‘Director’ undeclared (first use in this function)
Line Location HelloCocosAppDelegate.m:24: error: ‘scene’ undeclared (first use in this function)
Line Location HelloCocosAppDelegate.m:24: error: ‘Scene’ undeclared (first use in this function)
Line Location HelloCocosAppDelegate.m:26: error: ‘layer’ undeclared (first use in this function)
Line Location HelloCocosAppDelegate.m:26: error: ‘Layer’ undeclared (first use in this function)
Line Location HelloCocosAppDelegate.m:29: error: ‘label’ undeclared (first use in this function)
Line Location HelloCocosAppDelegate.m:29: error: ‘Label’ undeclared (first use in this function)

This is because we have not added the path to cocos2d header files.  Let’s address that next.  (You an also substitute Step6 and 7 by including Cocos2d source files into your project, described on the section Including Cocos2d Source Code Into Your Project located way below on this page.

Step6

Goto Project -> Edit Project Settings.

Open the Build tab and scroll down until you see Header Search Paths.

projectsettingsheadersearchpath

Double click to add paths.  You should enter the path where you copied the cocos2d SDK.  Something like: “Library/cocos2d-iphone-0.7.1/”  Hint: Do not include the “cocos2d” part in the folder name but make sure Recursive is checked; you can use finder and drag the folder into the dialog, saving you from typing.

headersearchpaths

Step7

Recompile.  You’ll get different errors:

“.objc_class_name_Scene”, referenced from:
literal-pointer@__OBJC@__cls_refs@Scene in HelloCocosAppDelegate.o
“.objc_class_name_Director”, referenced from:
literal-pointer@__OBJC@__cls_refs@Director in HelloCocosAppDelegate.o
“.objc_class_name_Label”, referenced from:
literal-pointer@__OBJC@__cls_refs@Label in HelloCocosAppDelegate.o
“.objc_class_name_Layer”, referenced from:
literal-pointer@__OBJC@__cls_refs@Layer in HelloCocosAppDelegate.o
ld: symbol(s) not found
collect2: ld returned 1 exit status

These errors is because we did not link the Cocos2d library so the compiled doesn’t know what Layer, Label, Director, and Scenes are.  To fix this, expand the Targets Group, then expand HelloCocos, then open the context menu for Link Binary With Libraries.  Select Add->Existing Files.  Select cocos2d.a which you compiled in the previous guide.  Ie: the cocos2d.a will be in a subfolder called build within your cocos2d folder.

Note here, you must add the correct library version for the target platform.  If you’re compiling for the simulator, select Debug-iphonesimulator, or Release-iphonesimulator.  If you’re compiling for an actual iPhone, select Debug-iphoneos, or Release-iphoneos.   addcocoslib

Step8

Recompile.  And voila, more errors.  Blah, more linker error, which usually means we forgot to include some frameworks.

Line Location Tool:0: collect2: ld returned 1 exit status
Line Location Tool:0: symbol(s) not found
Line Location Tool:0: -[PVRTexture createGLTexture] in libcocos2d.a(PVRTexture.o)
Line Location Tool:0: -[EAGLView swapBuffers] in libcocos2d.a(EAGLView.o)
Line Location Tool:0: -[EAGLView _createSurface] in libcocos2d.a(EAGLView.o)
Line Location Tool:0: “_glGetError”, referenced from:
Line Location Tool:0: -[Director initGLDefaultValues] in libcocos2d.a(Director.o)
Line Location Tool:0: “_glClearColor”, referenced from:
Line Location Tool:0: -[TextureAtlas drawNumberOfQuads:] in libcocos2d.a(TextureAtlas.o)
Line Location Tool:0: “_glDrawElements”, referenced from:
Line Location Tool:0: -[EAGLView _createSurface] in libcocos2d.a(EAGLView.o)
Line Location Tool:0: “_glGenFramebuffersOES”, referenced from:
Line Location Tool:0: -[AtlasNode draw] in libcocos2d.a(AtlasNode.o)
Line Location Tool:0: -[AtlasNode draw] in libcocos2d.a(AtlasNode.o)
Line Location Tool:0: -[LabelAtlas draw] in libcocos2d.a(LabelAtlas.o)
Line Location Tool:0: -[LabelAtlas draw] in libcocos2d.a(LabelAtlas.o)
Line Location Tool:0: -[ColorLayer draw] in libcocos2d.a(Layer.o)
Line Location Tool:0: -[ColorLayer draw] in libcocos2d.a(Layer.o)
Line Location Tool:0: “_glEnableClientState”, referenced from:
Line Location Tool:0: -[Texture2D(Drawing) drawInRect:] in libcocos2d.a(Texture2D.o)
Line Location Tool:0: -[Texture2D(Drawing) drawAtPoint:] in libcocos2d.a(Texture2D.o)
Line Location Tool:0: -[ColorLayer draw] in libcocos2d.a(Layer.o)
Line Location Tool:0: “_glDrawArrays”

This time we have some clue from the strings in the message.  The word “EAGL” means we need to link to OpenGL ES Framework.   OpenGL ES most likely also requires QuartzCore Framework.

To fix this, expand the Targets Group, then expand HelloCocos, then open the context menu for Link Binary With Libraries.  Select Add->Existing Framework.

This window should appear:

hellococosaddframework

Click on the + button below Linked Libraries.

Another window will appear.  In that window, select Frameworks, then add OpenGLES.framework and QuartzCore.framework.

quartzcore

Step9

Build and Run.  And… no more error, but the simulator crashes with something like this:

2009-04-05 03:16:12.145 CocoInvaders[3294:20b] Image is Null
2009-04-05 03:16:12.145 CocoInvaders[3294:20b] *** Terminating app due to uncaught exception ‘NSInvalidArgumentException’, reason: ‘*** -[NSCFDictionary setObject:forKey:]: attempt to insert nil value (key: fps_images.png)’

Apparently, it’s looking for fps_images.png, which is used to show frame-rate (I personally think this is a bug, the image should not be required if we’re not displaying the frame-rate).  Anyway, where is the image?  It should be in a Resource folder inside where you installed cocos2d (on mine, it’s at Resources/Images folder).  Go ahead and add the image into the Resource section of your HelloCocos project.  Hint: to save you from getting more errors, I’ll just tell you that you also should add Default.png (cocos2d splash screen), and Icon.png:

cocos2dresource

Xcode often behaves funky when you move around resources.  It’s best to do Build->Clean then do Build All; otherwise you might get into a situation where there’s no compile error, but when you run the iPhone simulator, the app crashes with a bunch of cryptic errors.

Step10

Run it.  Here’s mine:

hellococos2dsimulator

Including Cocos2d Source Code Into Your Project

There is another option to substitute for Step 5 to 7 and that is by including Cocos2d sources into your project. The drawback of this is that you need to distribute more files or change more paths if you move or pass your project to another computer. But if you want to do it this way, then:

In the Group & Files window, control-click on the project name, select Add Existing Files.

helococosaddfiles

Add the following Cocos2d folders into the project.   cocos2dincludes

 

Do NOT include the Demo folder.

You will be asked whether to “Copy files into the destination group’s folder?”  Check the box if you want to copy the Cocos2d source files into your project folder.  It’s up to you which option to chose, obviously making copies will make your project folder larger, but on the  other hand, it also makes it easier to distribute your project.

 

Note: this guide is written for cocos2d version 0.71. If you are using 0.73 or later and are having issues, check the following post:
https://permadi.com/blog/2010/03/cocos2d-compiling-hint/
https://permadi.com/blog/2010/03/cocos2d-for-iphone-migrating-0-71-to-0-73/