How to create buttons in cocos2d: simple, radio, and toggle
Like this post? Follow me on Twitter!
Buttons tutorial screenshot
When you are making a game in cocos2d, likely one of the first things you'll find yourself needing is buttons. this tutorial will show you how to create buttons in cocos2d step by step, starting with simple buttons and then covering toggle and radio buttons too. this tutorial assumes that you 've already gone through the tutorial on how to create a simple game with cocos2d, or have equivalent knowledge.
When I first started trying to add a button with cocos2d, I thought the best way to was to just create a Sprite representing the button and check for when the button was tapped. although this is definitely possible, there's a much easier way to create buttons in cocos2d-by using the cocos2d menu system.
The cocos2d menu system consists of a menu that has a number of menu items inside it. menu items can be either text or images, and the menu system contains logic for arranging menu items, highlighting items when they are tapped, toggling items, and more. so let's give it a shot and try to create a simple button the cocos2d way!
Creating a simple button
Create a new project in xcode using the cocos2d application template, and name your project "ccbuttons. "Next you need some images of buttons to work with-you can either use your own, or download some button images I have created. once you have the images, drag them into your resources folder and make sure "Copy items into destination group's folder (if needed)" is checked.
Open up helloworldscene. h under classes and add a member variable to the helloworld class, we'll need this in a bit:
Then before we forget go to helloworldscene. M and add the cleanup code to the dealloc method:
[_label release];_label = nil; |
OK now for the good stuff. In the same file (helloworldscene. m), replace the init method with the following code:
-(id) init{ if( (self=[super init] )) { CGSize winSize = [[CCDirector sharedDirector] winSize]; // Create a label for display purposes _label = [[CCLabelTTF labelWithString:@"Last button: None" dimensions:CGSizeMake(320, 50) alignment:UITextAlignmentCenter fontName:@"Arial" fontSize:32.0] retain]; _label.position = ccp(winSize.width/2, winSize.height-(_label.contentSize.height/2)); [self addChild:_label]; // Standard method to create a button CCMenuItem *starMenuItem = [CCMenuItemImage itemFromNormalImage:@"ButtonStar.png" selectedImage:@"ButtonStarSel.png" target:self selector:@selector(starButtonTapped:)]; starMenuItem.position = ccp(60, 60); CCMenu *starMenu = [CCMenu menuWithItems:starMenuItem, nil]; starMenu.position = CGPointZero; [self addChild:starMenu]; } return self;} |
First we create a label for debugging purposes. this shoshould look pretty familiar-we did this in the last tutorial. however you'll notice we're re using a new constructor this time that allows us to specify the dimensions of the label and the alignment. this way we specify the label size to be as wide as the window, and that the text shoshould be centered. this is a handy technique to know, especially when you want to left or right justify text.
Next is the code where we create the button. we first create a menu item of class ccmenuitemimage and specify a selected and unselected image for the button. when we create the menu item, we specify a callback function to be called when the button is tapped (we'll write this in a second ). the last step is to create a menu to contain the button (or buttons ).
Note that we create the menu at cgpointzero (a shortcut cut for 0, 0 ). this is actually specifying where the center of the menu is. however, we also specify that the menu item is at offset (60, 60) relative to the center of the menu-So our button's center is at (60, 60) on the screen.
OK, one last bit of code to add. Underneath init Add the callback function that will be called when the button is tapped:
- (void)starButtonTapped:(id)sender { [_label setString:@"Last button: *"];} |
Give it a compile and run, and if all goes well you shoshould see the following:
Toggle buttons
Another common type of button you'll need in an iPhone game is a toggle button. this is a button that has one image on it, until you tap it and it switches to another image. this cocould be used to toggle visibility of a control panel to make the best use of the limited screen real estate on the iPhone.
Luckily, cocos2d comes with a special menu item class called ccmenuitemtoggle that makes this easy. Let's give this a shot! First add two more member variables to helloworldscene. h:
CCMenuItem *_plusItem; CCMenuItem *_minusItem; |
And add the following cleanup code in your dealloc method:
[_plusItem release];_plusItem = nil;[_minusItem release];_minusItem = nil; |
Then add the following code in your init method right after you add the startmenu to the scene:
_plusItem = [[CCMenuItemImage itemFromNormalImage:@"ButtonPlus.png" selectedImage:@"ButtonPlusSel.png" target:nil selector:nil] retain];_minusItem = [[CCMenuItemImage itemFromNormalImage:@"ButtonMinus.png" selectedImage:@"ButtonMinusSel.png" target:nil selector:nil] retain];CCMenuItemToggle *toggleItem = [CCMenuItemToggle itemWithTarget:self selector:@selector(plusMinusButtonTapped:) items:_plusItem, _minusItem, nil];CCMenu *toggleMenu = [CCMenu menuWithItems:toggleItem, nil];toggleMenu.position = ccp(60, 120);[self addChild:toggleMenu]; |
First we create two ccmenuitemimages, just like we did in our previous example. then comes the twist-we add both of those into a ccmenuitemtoggle. this class keeps Toggles between the elements inside, and keeps track of which is currently visible.
Note that we set the callbacks to nil when we created the ccmenuitemimages, but set it on the ccmenuitemtoggle. this is to make it clear that any selectors on the ccmenuitemimages will not be called when they are inside a ccmenuitemtoggle-only the ccmenuitemtoggle's selector will be called. luckily, we can easily tell which of the menu items is visible in the callback.
Let's see how by writing the callback! Add the following after your init method:
- (void)plusMinusButtonTapped:(id)sender { CCMenuItemToggle *toggleItem = (CCMenuItemToggle *)sender; if (toggleItem.selectedItem == _plusItem) { [_label setString:@"Visible button: +"]; } else if (toggleItem.selectedItem == _minusItem) { [_label setString:@"Visible button: -"]; } } |
So as you can see, the ccmenuitemtoggle has a selecteditem property that can show us which of the sub-items is currently visible (note it means visible, not which was tapped !)
So give it a compile and run, and if all goes well you shoshould see the following:
Radio buttons
A third common type of button that you might need in your iPhone projects are radio buttons. I found I needed some radio buttons for a game I was working on, but didn't see an implementation for radio buttons in the cocos2d source, so wrote an implementation of my own. while I was writing this article I came into SS two other guys who wroteimplementations for radio button support in cocos2d as well-so it looks like this will find its way into the cocos2d source soon.
But it's not in there yet, so in the meantime feel free to use the implementation I wrote or the ones I referenced above. for the purpose of this tutorial, let's implement radio buttons using the implementation I wrote. first, download ccradiomenu. H and ccradiomenu. m and drag them to the classes directory of your project (making sure "copy items into destination group's folder (if needed)" is checked ). then add the following import to the top of helloworldscene. m:
And the following to your init method after you add the toggle menu to the scene:
CCMenuItem *menuItem1 = [CCMenuItemImage itemFromNormalImage:@"Button1.png" selectedImage:@"Button1Sel.png" target:self selector:@selector(button1Tapped:)];CCMenuItem *menuItem2 = [CCMenuItemImage itemFromNormalImage:@"Button2.png" selectedImage:@"Button2Sel.png" target:self selector:@selector(button2Tapped:)];CCMenuItem *menuItem3 = [CCMenuItemImage itemFromNormalImage:@"Button3.png" selectedImage:@"Button3Sel.png" target:self selector:@selector(button3Tapped:)];CCRadioMenu *radioMenu = [CCRadioMenu menuWithItems:menuItem1, menuItem2, menuItem3, nil];radioMenu.position = ccp(120, 180);[radioMenu alignItemsHorizontally];radioMenu.selectedItem = menuItem1;[menuItem1 selected];[self addChild:radioMenu]; |
We create the ccmenuitemimages like usual, but instead of adding them to a ccmenu we add them to the new ccradiomenu class. this class makes sure only one is selected at a time. we also set the first item to be selected by default at start.
The other new thing here is we call alignitemshorizontally on the menu to take advantage of the neat auto-layout capability in cocos2d. note that the items will be laid out with respect to the center of the menu. therefore, we can no longer center the menu at position (0, 0)-we have to move the center up and to the right a bit where we want the items to display.
One last thing to add-the callback methods as usual:
- (void)button1Tapped:(id)sender { [_label setString:@"Last button: 1"];} - (void)button2Tapped:(id)sender { [_label setString:@"Last button: 2"];} - (void)button3Tapped:(id)sender { [_label setString:@"Last button: 3"];} |
Once you compile and run this You shoshould see something like the following:
Behind the scenes
If you look at how the menu system is implemented, you will note that menu items are ccnodes, but a menu is a cclayer. according to the cocos2d class reference, you shouldn't create a big hierarchy of layers, and shoshould keep the count as low as you can.
So this means you probably shoshould combine as your menu items into a single menu layer as you can. also since a menu derives from cclayer you can't make it run actions such as moveTo, etc. I only mention this because I tried to move a whole menu of items when I was first starting and was wondering why it didn't work:]Update:Eric from the comments below pointed out that cclayer derives from ccnode, so you can run actions on it if you need. something else must have been going on when I was playing with it earlier, Thanks Eric! :]
And that's a wrap!
Here's a project with all of the code from the above tutorial.
Hope this was of use, and if you have any other cool tips about buttons in cocos2d please let me know!
Category: iPhone
//////////////////////////////////////// //////////////////////////////////////// //////////////////////////////////////// //////////////////////////////////////// //
Http://www.raywenderlich.com/414/how-to-create-buttons-in-cocos2d-simple-radio-and-toggle