"COCOS2DX" uses Cccontrolbutton to create buttons, button click events, click on components in events to get, setposition coordinate problems

Source: Internet
Author: User
Tags addchild

Button not only in the game, in any place is indispensable but also the most basic thing. In the game engine COCOS2DX is no exception.

Here's an example of how buttons are used in COCOS2DX, and if you get a layer in cocos2dx, that is, the scene, the component in the stage.

For example, there is a button clickme, the time that is clicked with not being clicked, its background picture is different. In fact, the Resource folder resource has been playing a bad two pictures, a closenormal.png a closeselected.png was stretched after the horrors.

COCOS2DX's resource folder has been described in the "COCOS2DX" Resource folder, playing background music, importing external libraries (click the Open link).

How to stretch the picture, please refer to "COCOS2DX" to stretch the picture with Ccscale9sprite (click to open link)

When clicked, the text above it, the number of clicks on the change. Click once to add one more time.


1, first or the same old, using the command line to create a project, this I will not say, you can refer to the "COCOS2DX" Windows platform cocos2dx 2.x download, installation, configuration, build their own HelloWorld "(Click to open the link)

2, after, open./projects/project name/proj.win32/hellocpp.sln, and "cocos2dx" new scene, Scene switch, set start scene and Menu new "(click Open link), Set Pdirector->setdisplaystats (FALSE) in line 22nd of AppDelegate.cpp first, and turn off debugging to make changes directly to the HelloWorld scene. First open HelloWorldScene.h This file, the original HelloWorld scene header file is too bloated, you can delete some useless cross-platform macro compilation information, the key is the inside of the 4 function declaration, mainly the 3rd function declaration to expand the parameters to match the button click event cccontr Ol_selector, if the 2nd argument is not added, the Cccontrolevent event is not compiled.

HelloWorldScene.h the full code after this file has been modified is as follows:

#include "cocos2d.h" #include "cocos-ext.h"//Use the button event, the header file that must be required using_ns_cc_ext;//use the button event, the namespace class HelloWorld that must be required: Public cocos2d::cclayer{public:    //Here ' s a difference. Method ' init ' in cocos2d-x returns BOOL, instead of the returning ' ID ' in cocos2d-iphone    virtual bool init ();      There ' s no ' id ' in CPP, so we recommend returning the class instance pointer    static cocos2d::ccscene* scene ();        A selector callback    void Menuclosecallback (ccobject* psender,cccontrolevent event);//modification of the original shutdown events, increased parameters, Let IT support cccontrol_selector        //Implement the "Static node ()" Method manually    Create_func (HelloWorld);};
3, after the HelloWorldScene.cpp this file in the bool Helloworld::init () {} scene initialization layout function, originally HelloWorld scene, Click on the lower right button of the callback function Menuclosecallback to modify. The code after the modification is as follows, see note:

#include "HelloWorldScene.h" #include "cocos-ext.h"//Use the button event, you must need the header file using_ns_cc; using_ns_cc_ext;//use a button event, you must need the namespace int hits=0;//global variable, used to count clicks of the number of clicks ccscene* helloworld::scene () {//' scene ' is an        Autorelease object Ccscene *scene = Ccscene::create ();    ' Layer ' is an Autorelease object HelloWorld *layer = Helloworld::create ();    Add layer as a child to scene scene->addchild (layer); Return the scene return scene;} On "Init" need to initialize your Instancebool helloworld::init () {//Get screen size, location information, etc. ccsize visiblesize = Ccdirec     Tor::shareddirector ()->getvisiblesize (); The Claim button section cocos2d::extension::ccscale9sprite *btn_noraml = Cocos2d::extension::ccscale9sprite::create (" Closeselected.png ");//Declaration closenormal picture, used for the background picture when the button is not pressed cocos2d::extension::ccscale9sprite *btn_down = cocos2d:: Extension::ccscale9sprite::create ("Closenormal.png");//Declaration closeselected picture, for the background picture when the button is pressed Cclabelttf *labelttf = Cclabelttf::create ("Click me!", "Arial", 72);//Declare a text Click me!2 parameters are fonts, only the fonts in the Fonts folder in the Resource folder can be used, the 3rd parameter is the font size Cccontrolbutton *controlbutton = cccontrolbutton::create (Labelttf, BTN_NORAML);//Declare a button, the first argument is the declared text, the second argument is the declared picture Controlbutton->setbackgroundspriteforstate (Btn_down, cccontrolstatehighlighted);///Set the background image when the button is pressed, the first parameter is the declared picture, the second parameter is a constant value controlbutton->setposition (CCP ( VISIBLESIZE.WIDTH/2,VISIBLESIZE.HEIGHT/2));//The center point of the button is located in the middle of the screen controlbutton-> Addtargetwithactionforcontrolevents (This, Cccontrol_selector (Helloworld::menuclosecallback), Cccontroleventtouchdown);//Declare the event of the button, the third parameter is constant meaning, after clicking this button, trigger the second function to declare, the following Helloworld::menuclosecallback () {} All the code in the. This->addchild (Controlbutton);//Add this button to the scene, default does not automatically add//Declare the file part Cclabelttf *label1 = Cclabelttf::create ("0 hits", " Arial ", 36);//declaration of a literal 0 hits!label1->setposition (CCP (visiblesize.width/2,visiblesize.height-visiblesize.height/ 6);//The center point of the button is located in the central this->addchild of the screen (label1,0,1);//Add this text to the scene, unlike the normal This->addchild (Label1), the 3rd parameter can be understood as the tag of this file , which is something similar to the ID in other programming languages, and in a moment, when the button hits the trigger Menuclosecallback function, this function can be this->geTchildbytag (1); Gets the literal return true;} Controlbutton is clicked, the event that is triggered Menuclosecallbackvoid helloworld::menuclosecallback (ccobject* psender,cccontrolevent Event) {hits++;//Click this number +1cclabelttf *label= (cclabelttf*) This->getchildbytag (1);//Get TAG1 1 component, point to label-with the label pointer >setstring (Ccstring::createwithformat ("%d hits", hits)->getcstring ());//modify it to Xxhits, Which createwithformat use the same C language as printf, do not repeat}

Several key points:

(1) Menuclosecallback () and init () Add the component Addchild time, set the Labelttf tag, and Menuclosecallback () Getchildbytag Gets the tag 1 component and interacts with Android's Findviewbyid coercion type conversion.

(2) The Addchild is set by the SetPosition method before it is added to the assembly. Where the coordinates in SetPosition, must survive the CCP in this method, CCP can not directly write numbers, it is recommended to display the component by cocos2dx screen percentage. The layout of this program is as follows:


The screen coordinates of the cocos2dx are, in the lower left corner of the screen, as the origin, the right side of the screen is the x-axis positive direction, the upper screen is the Y-positive axis. where the x-axis values range from 0 to Visiblesize.width,y is 0 to Visiblesize.height, where visiblesize is required through ccsize visiblesize = ccdirector: Shareddirector ()->getvisiblesize ();

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

"COCOS2DX" uses Cccontrolbutton to create buttons, button click events, click on components in events to get, setposition coordinate problems

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.