cocos2d – Basic Menu

I figure I will start off with something nice and simple. All apps need a menu and games are of course no different. With cocos2d is is fairly simple to create a menu.

I’m going to presume you already have cocos2d installed and the templates installed. You are going to need at least two images, a button-up state image and a button-down state image. You could also create “-hd” versions of these for the iPhone 4.

1. Start off by creating a new cocos2d application.

2. Add your button-up and button-down images to the resources by dragging them into it. Copy them to your project.

3, Find the HelloWorldScene.m file and the remove the code between the if statements

// 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] )) {
		
		// create and initialize a Label
		CCLabelTTF *label = [CCLabelTTF labelWithString:@"Hello World" fontName:@"Marker Felt" fontSize:64];

		// ask director the the window size
		CGSize size = [[CCDirector sharedDirector] winSize];
	
		// position the label on the center of the screen
		label.position =  ccp( size.width /2 , size.height/2 );
		
		// add the label as a child to this Layer
		[self addChild: label];
	}
	return self;
}

Becomes

// 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] )) {
	}
	return self;
}

4. Add you menu items. These will be CCMenuItemImage items.

CCMenuItemImage *item1 = [CCMenuItemImage itemFromNormalImage:@"item1.png" selectedImage:@"item1Down.png" target:self selector:@selector(menuAction1:)];	
CMenuItemImage *item2 = [CCMenuItemImage itemFromNormalImage:@"item2.png" selectedImage:@"item2Down.png" target:self selector:@selector(menuAction2:)];	

The code is here is fairly self explanatory. Substituting your image names for me add this code between the if statement in the init method. “menuAction1” and “menuAction2” are methods that are called one touching the menu item

5. Create the menu
Add the after the code you added above.

CCMenu *menu = [CCMenu menuWithItems:item1, item2, nil];
[menu alignItemsVertically];

6. Add the menu to the scene

[self addChild: menu];

7. FInally you need to add the event methods to .h and .m files
.m

-(void) menuAction1: (id) sender
{
// do something
}
-(void) menuAction2: (id) sender
{
// do something
}
.h
-(void) menuAction1:(id) sender;
-(void) menuAction2:(id) sender;

And that’s about all there is to it.

I know this is a little breif, so feel free to ask if you have any questions. I will try make my future posts more detailed if time permits.

One Reply to “cocos2d – Basic Menu”

Comments are closed.