How to create buttons in cocos2d: simple buttons, single-choice buttons, and switch buttons

Source: Internet
Author: User

Disclaimer (read only !) : The original translations of all tutorials provided by this blog are from the Internet and are only for learning and communication purposes. Do not conduct commercial communications. At the same time, do not remove this statement when reprinting. In the event of any dispute, it has nothing to do with the owner of this blog and the person who published the translation. Thank you for your cooperation!

Original article link: http://www.raywenderlich.com/414/how-to-create-buttons-in-cocos2d-simple-radio-and-toggle

Program:

When you are using cocos2d to create a game, you may find that the first thing you need is a "button ". (For example, the menu selection interface at the beginning of the game) This tutorial will teach you how to use cocos2d to create buttons step by step. Create a simple button at the beginning, and then introduce the switch button and single choice button. This tutorial assumes that you have read a series of tutorials on how to use cocos2d to create a simple iPhone game, or have the same experience.

When I first wanted to add a button in cocos2d, I thought like this: Create a sprite to represent the button, and then check when the button is pressed. Of course, this is certainly feasible. However, there is a simpler way in cocos2d-by using the cocos2d menu system.

The cocos2d menu system contains a menu and a series of menuitems. Menu items can be text or images, and the menu system also contains some very useful logic, such as: arranging menu items, highlighting the menu items that are pressed down, switch menu items. Let's take a look at how to create a simple button in cocos2d mode!

Create a simple button

Open xcode, use cocos2d application template to create a new project and name it ccbuttons. Next, you need some button images-you can create them yourself, or download some images that I have prepared. Now that you have images, drag them under the Resource folder and make sure to select "Copy items into destination group's folder (if needed )".

Open the helloworldscene. h file under the classes group, and add a member variable to the helloworld class, which will be used later:

Cclabelttf * _ Label;

Then, to prevent the memory cleanup operation from being forgotten, open helloworldscene. M and add some cleanupCode:

 

[_ Label release];
_ Label = Nil;

Well, the next step is the focus. Similarly, in the helloworldscene. M file, replace the init method with the following code:

- (ID) Init
{
If (Self = [Super init]) {

Cgsize winsize=[[Ccdirector shareddire] 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];

}
ReturnSelf;
}

First, we created a label for ease of debugging. This looks familiar, right? --- We mentioned this in the previous tutorial. However, this time we use a new constructor that allows us to specify the label size and text alignment. Here, I set the label size to the same width as the window size, and the text needs to be centered and aligned. This is a well-known technique, especially when you want to implement some left-aligned or right-aligned text.

The following code is the create button. Use the ccmenuitemimage class to create a menu item, and specify a selected image and an unselected image for this button. (That is, the image to be clicked and the image not to be clicked) after the menu item is created, we specify a callback function for the button click event (the code will be provided later ). The last step is to create a menu to include this button (or a series of buttons ending with nil ).

Note that a button is created at the position of cgpointzero (origin. The center of the menu is actually specified here. Then, we specify the offset between the position of the menu item and the position of the menu item (60, 60) -- in this way, when displayed on the screen, the menu item will be displayed at (60, 60. (Because the position of a menu item is relative to the center of the menu, set the center of the menu to (0, 0, you can easily specify coordinate points for each menu item, because at this time, you only need to set the coordinate points for the menu item when the button appears on the actual screen ).

Well, there are some code to add. After the init method, add our button callback function:

- ( Void ) Starbuttontapped :( ID) sender {
[_ Label setstring: @" Last button :* " ];
}

Compile and run. You will see the following running results:

Switch button

Another commonly used button type in iPhone games is the switch button. This type of button only shows one image at a time. When you click it, it switches to another image. This can be used to create a controller for control panel visibility, so that the limited screen size on the iPhone can be used to the maximum extent.

Fortunately, cocos2d has a built-in menu item called ccmenuitemtoggle, which makes things easier. Let's try it out! First, add two member variables in helloworldscene. h:

Ccmenuitem * _ Plusitem;
Ccmenuitem * _ Minusitem;

Then add the following cleanup code in the dealloc method:

[_ Plusitem release];
_ Plusitem = Nil;
[_ Minusitem release];
_ Minusitem = Nil;

Then, after the startmenu you added for the scenario, add the following code:

_ 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, create two ccmenuitemimages, just as in the previous example. Here is a little different -- I added them to ccmenuitemtoggle. This class manages the menu items that should be displayed and switches between the switching elements.

Note: When creating ccmenuitemimage, I set the callback function to nil, but I set the callback function for the ccmenuitemtoggle class. This will make the code clearer: When ccmenuitemimage is in ccmenuitemtoggle, no selector on ccmenuitemimage will be called, but only the selector of ccmenuitemtoggle will be called. Of course, we can easily distinguish which menu item is visible in the callback function.

Next, let's take a look at how to implement the callback function! Add the following code after the 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 :- " ];
}
}

Therefore, as you can see, ccmenuitemtoggle has a selecteditem attribute, which tells us which sub-menu item is currently visible (note that the items currently visible are not equal to those clicked)

Okay. Let's run it! You will see the following results:

Radio button

The third common button type is the single-choice button (radio button). When I was playing a game, I found that I needed some single-choice buttons. However, cocos2dSource codeThere is no single-choice button implementation. Therefore, we implement a single-choice button. Then, when I was writing this tutorial, I found that the other two also wrote "How to support single-choice buttons in cocos2d"Article-- This means that in the near future, you will see the implementation of the radio button in the cocos2d source file.

Currently, cocos2d does not exist. Therefore, during this period, you can use some of the implementations I mentioned above for free. This tutorial uses the implementation of the radio button I wrote myself. First, download the ccradiomenu. h and ccradiomenu. m, and drag them to your classes group (make sure to check ""). Then add the following code at the top of helloworldscene. M:

# Import " Ccradiomenu. h "

Next, follow the code behind the init method to add the switch button. Add the following code:

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];

First, create a ccmenuitemimage as before, but we do not add it to the ccmenu class, but add them to the ccradiomenu class. This class ensures that only one menu item is selected at a time. By default, the first menu item is selected.

Here is a new knowledge point: we use the layout function in cocos2d to call the menu's alignitemshorizontally to horizontally align all menu items in the menu. Note that menu items are arranged relative to the center of the menu. Therefore, we no longer need to set the menu center to (0, 0). Instead, we need to move the menu to the center to the right, in this way, all menu items can be displayed completely.

Last thing -- add the callback function as before:

- ( 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"];
}

 

Compile and run the program. You will see the following results:

Principles behind

If you look at how the menu system is implemented, you will notice that all menu items are subclasses of ccnode, but menu is a subclass of cclayer. According to cocos2d best practices, you should not create a very large level structure, you should make the level as small as possible.

Therefore, this means that you may need to put as many menu items as possible in one menu. Because cclayer is derived from ccnode, it can also run action. That is to say, you can run the action on menu.

Summary

The complete source code of this tutorial is provided here. I hope this tutorial will be helpful to you. If you have any good comments or good ideas when using the cocos2d button, please share it with me!

 

Copyright statement: This article consistsHttp://www.cnblogs.com/andyquetranslation. You are welcome to enjoy the conversion and sharing. Please respect the work of the author. Keep this note and the author's blog link when reprinting. Thank you!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.