Mac / iPhone App Development
Home of a Small Time Developer

Cocos2d iphone tutorial

Cocos2d is a popular 2d framework for developing iphone games, including physics and particle support.  Here’s a quick introduction to getting cocos2d for the iphone up and running for your next project.

Download the latest source from:

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

I recommend you stick with the stable releases, unless there is a specific feature your require from a new version.

Unzip the folder and the template installation script:

$ ./install_template.sh

This will make a series of cocos-2d templates available from XCode.  Launch/restart xcode and choose File->New Project->cocos2d Application build and run the new application in the simulator and it should look something like this:

Were going to build on this template to add a main menu

First download the test image and add it to the new xcode project (Make sure it is copied into the application directory)

Create a new class name MenuScene and add the following code to the header file:

#import
#import "cocos2d.h"

@interface MenuScene : Scene
{

}

@end

@interface MenuLayer : Layer
{
}

-(void)startGame: (id)sender;
-(void)help: (id)sender;

@end

The add the following to the .m file:

#import "MenuScene"

@implementation MenuScene

- (id) init
{
    self = [super init];
    if (self != nil) {
        Sprite * bg = [Sprite spriteWithFile:@"MainMenuBackground.png"];
        [bg setPosition:ccp(160, 240)];
        [self addChild:bg z:0];
        [self addChild:[MenuLayer node] z:1];
    }
    return self;
}

@end

@implementation MenuLayer

- (id) init
{
    self = [super init];
    if (self != nil)
	{
        [MenuItemFont setFontSize:24];
        [MenuItemFont setFontName:@"Helvetica"];

        MenuItem *start = [MenuItemFont itemFromString:@"Start Game"
												target:self
											  selector:@selector(startGame:)];

        MenuItem *help = [MenuItemFont itemFromString:@"Help"
											   target:self
											 selector:@selector(help:)];

        Menu *menu = [Menu menuWithItems:start, help, nil];
		menu.color = ccc3(0, 0, 0);

        [menu alignItemsVertically];
        [self addChild:menu];
    }
    return self;
}

-(void)startGame: (id)sender
{
    NSLog(@"start game");
}

-(void)help: (id)sender {
    NSLog(@"help");
}

@end

Finally modify the app delegate (CocosTestAppDelegate.m) to include MenuScene.h

#import "MainMenuScene.h"

and replace the line:

[[Director sharedDirector] runWithScene: [HelloWorld scene]];

with:

[[Director sharedDirector] runWithScene: [MenuScene node]];

also remove the line:

[[Director sharedDirector] setDeviceOrientation:CCDeviceOrientationLandscapeLeft];

Compile and run the project and you should end up with a menu and two clickable buttons:

Leave a Reply