Sunday, August 14, 2011

Adding Pause/Play Buttons to your iPhone Game using Cocos2d

In developing the iPhone version of Word Crank it took me a while to figure out how to add the pause/play buttons using Cocos2d.  One post that I found suggested using the CCMenuItemToggle class of Cocos2d.  That is exactly what I used and after some playing around with the code I finally was able to get the the pause/play buttons to function properly.

I'm sharing the code below to assist others from going through the endless search that I made.

Source Code


[sourcecode language="objc"]
CCSprite *pauseButton = [CCSprite spriteWithSpriteFrameName:@"pause_button.png"];
CCSprite *pauseButton2 = [CCSprite spriteWithSpriteFrameName:@"pause_button.png"];

CCSprite *playButton = [CCSprite spriteWithSpriteFrameName:@"play_button.png"];
CCSprite *playButton2 = [CCSprite spriteWithSpriteFrameName:@"play_button.png"];

pauseBtn = [[CCMenuItemImage itemFromNormalSprite:pauseButton
selectedSprite:pauseButton2
target:nil
selector:nil] retain];

playBtn = [[CCMenuItemImage itemFromNormalSprite:playButton
selectedSprite:playButton2
target:nil
selector:nil] retain];

CCMenuItemToggle *toggleItem = [CCMenuItemToggle itemWithTarget:self
selector:@selector(pausePlayButtonTapped:)
items:pauseBtn, playBtn, nil];

// Create a menu and add your menu items to it
CCMenu *pausePlayMenu = [CCMenu menuWithItems:toggleItem, nil];
pausePlayMenu.position = ccp(300, 56);
[self addChild:pausePlayMenu z:10];
[/sourcecode]

Source Code Notes


One thing to notice is that I had to create 2 Sprites for each of the pause and play buttons because Cocos2d doesn't let you add the same Sprite twice to create the MenuItem object.

Download Word Crank on Android for FREE!

2 comments:

  1. You can click the signup button at the bottom right of the Home page, that will allow you to receive all of the updates. Thanks for your support!

    ReplyDelete
  2. You don't have to use pauseButton2 and playButton2. Just pass nil instead.

    ReplyDelete