Last time we talked about creating a simple menu in cocos2d. This tutorial will show you how to use CCMenuItemToggle to create a simple sound on/off button using images to represent the two states.
Create a new cocos2d application, or use the application from the last tutorial. We'll need to use some images for the on/off states, so add the following images to your project's Resources group:
In the scene where you would like to place your sound on/off button, add the following code to your init method:
// Sound on/off toggle CCMenuItem *soundOnItem = [CCMenuItemImage itemFromNormalImage:@"soundOn.png" selectedImage:@"soundOn.png" target:nil selector:nil]; CCMenuItem *soundOffItem = [CCMenuItemImage itemFromNormalImage:@"soundOff.png" selectedImage:@"soundOff.png" target:nil selector:nil]; CCMenuItemToggle *soundToggleItem = [CCMenuItemToggle itemWithTarget:self selector:@selector(soundButtonTapped:) items:soundOnItem, soundOffItem, nil];
First, we create two menu items from our sound on/off images. They'll just be used as reference for our toggle item, so we just set our target and selector to nil.
Next, we create the actual CCMenuItemToggle. The target will be self, and we'll specify a soundButtonTapped: method for our selector (which we'll create later). Then, we add our soundOnItem and soundOffItem to the toggle.
Now, we'll create a menu to add our soundToggleItem:
CCMenu *bottomMenu = [CCMenu menuWithItems:soundToggleItem, nil]; soundToggleItem.position = ccp( -90,-120); [self addChild: bottomMenu z: 10];
Finally, let's just add our method for when the sound button is tapped:
-(void) soundButtonTapped: (id) sender { // do something… maybe even turn the sound on/off! NSLog(@"Sound button tapped!"); }
Build and run, and you should see a sound on/off button that changes state each time you tap it.
0 comments:
Post a Comment