Cocos2dx 3.1 learning from scratch (2) -- menu, scenario switching, and scenario value passing

Source: Internet
Author: User

Looking back at the previous article, we have learned to create a new scene, add sprite and label to the layer, and master the scheduled event schedule. We can smoothly write out the main scenario framework for aircraft logging.

In the previous article, I practiced seven new scenarios. Each scenario shows different things, such as regular background switching and random colors and positions of various fonts. Every time you want to switch to a scenario, you need to modify the call code in AppDelegate, which is very inconvenient to view. This article describes how to switch to a scenario. When we create a new scenario, we only need to add the corresponding button to the main interface, and click it to switch to view the corresponding effect. This is a bit similar to the official cpptest viewing method, so scenario switching is very easy to use.

 

To click the switch scenario, you must have a button to receive messages. So first, learn about the Menu ):

Menu creation Menu

Create MenuItem Create menu item

MenuItemFont is a menu item.

auto item= MenuItemFont::create("Hello,Menu",CC_CALLBACK_1(MenuScene::Menutest, this));

"Hello, Menu" is the text of the Menu subitem button.

MenuScene: Menutest is a callback function. Its parameter is Menutest (Ref * pSender). You can view the create definition to obtain the parameter type.

CC_CALLBACK_1 is bound to a function as the callback function. _ 1 indicates that this function has only one parameter.

 

The first menu can be written as follows:

// The first four sentences must be the auto item = MenuItemFont: create ("Hello, Menu", CC_CALLBACK_1 (MenuScene: Menutest, this); auto menu = Menu: create (); menu-> addchild (item); this-> addchild (menu); voidMenuScene: Menutest (Ref * ref) {// you can add an genie here. Each time you click the menu button, a wizard is added to the scene .}

You can also create a menu like this without calling menu-> addchild (item) every time ):

Auto item = MenuItemFont: create ("Hello, Menu", CC_CALLBACK_1 (MenuScene: Menutest, this); auto item1 = MenuItemFont: create ("Ruck, Menu ", CC_CALLBACK_1 (MenuScene: Menutest1, this); auto item2 = MenuItemFont: create ("Click, Menu", CC_CALLBACK_1 (MenuScene: Menutest2, this )); auto item3 = parameters: create ("KTWork", CC_CALLBACK_1 (MenuScene: KTWork, this); auto item4 = MenuItemFont: create ("PushScene", CC_CALLBACK_1 (MenuScene :: pushScene, this); auto item5 = MenuItemFont: create ("HomeWork", CC_CALLBACK_1 (MenuScene: HomeWork, this); auto item6 = MenuItemFont :: create ("HomeWork0617", CC_CALLBACK_1 (MenuScene: HomeWorkSnow, this); auto item7 = parameters: create ("KT0618", CC_CALLBACK_1 (MenuScene: KT0618, this )); auto menu = Menu: create (item, item1, item2, item3, item4, item5, item6, item7, <span style = "color: # ff0000;"> NULL ); // note that the last parameter is null </span> menu-> setPosition (Director: getInstance ()-> getVisibleSize (). width/2, Director: getInstance ()-> getVisibleSize (). height/2); menu-> alignItemsVerticallyWithPadding (40); // you can see that it is a vertical alignment interval of 40 pixels. this-> addchild (menu );

In the callback function, perform the following operations on the properties of the menu item:

VoidMenuScene: Menutest1 (Ref * ref ){

MenuItemFont * item = (MenuItemFont *) ref; // The base class Ref of all classes. We create an item through MenuItemFont in the menu, therefore, you can forcibly convert the Data Type Back To The MenuItemFont type in the callback function. Then you can modify the attributes of the menu item in the callback function.

    if (item->getColor() == Color3B::RED)    {        item->setColor(Color3B::GREEN);        item->setFontSizeObj(55);       item->setFontNameObj("Baskerville-Boldltalic");       item->setString("GreenClick");    }    else    {        item->setColor(Color3B::RED);        item->setFontSizeObj(24);       item->setFontName("Baskerville-Boldltalic");       item->setString("RedClick");    }}

From the code above, we can see that there are many sub-items in the menu I created. These sub-items are scenario switching. Every new scenario is an exercise.

See:


 

There are many ways to create a menu item:

MenuItemLabel, MenuItemImage, MenuItemSprite, etc.

Below take MenuItemLabel example (futura-48.fnt in my first article aircraft source code material, source code on the first floor, this font in addition to fnt there is a png file, is together, can not be separated. The menu created in this font is highlighted in yellow .)

Autoitem2 = MenuItemLabel: create (Label: createWithBMFont ("fonts/futura-48.fnt", "Start"), CC_CALLBACK_1 (MenuSceneTwo: MenuTest, this ));

For details, see the following:

This is my first Hello, Menu scenario.



The menu creation has been introduced above. try to create a new scenario. click the button to switch between different backgrounds.

Bind data to the menu item

Here, we also want to learn the two operation functions of the sub-item. SetUserData and setUserObject.

SetUserData is defined to receive the void * parameter, which can receive any type of data. We can use it to transmit the basic data of C ++, but do not use new variables to pass values, which may cause exceptions.

SetUserObject receives child classes inherited from Ref. The subclass inherited from Ref. The most common one is the String of cocos2dx.

    auto item1 = MenuItemLabel::create(Label::createWithBMFont("fonts/futura-48.fnt", "Easy"), CC_CALLBACK_1(HomeWorkSnow::Start, this));    item1->setUserObject(String::create("Easy"));    auto item2 = MenuItemLabel::create(Label::createWithBMFont("fonts/futura-48.fnt", "Hard"), CC_CALLBACK_1(HomeWorkSnow::Start, this));    item2->setUserObject(String::create("Hard"));    auto item3 = MenuItemLabel::create(Label::createWithBMFont("fonts/futura-48.fnt", "Difficult"), CC_CALLBACK_1(HomeWorkSnow::Start, this));    item3->setUserObject(String::create("Difficult"));    auto item4 = MenuItemLabel::create(Label::createWithBMFont("fonts/futura-48.fnt", "Hell"), CC_CALLBACK_1(HomeWorkSnow::Start, this));    item4->setUserObject(String::create("Hell"));    auto menu = Menu::create(item1, item2, item3, item4, NULL);    addChild(menu);    menu->alignItemsVertically();

We need to extract the set data. The corresponding two functions are getUserData and getUserObject.

In the menu response callback function, we can perform the following operations:

void  HomeWorkSnow::Start(Ref *ref){    MenuItemLabel *item = (MenuItemLabel*)ref;    String * str = (String *)item->getUserObject();    auto scene = HomeWorkSnowFight::createScene();    HomeWorkSnowFight *layer = (HomeWorkSnowFight*)scene->getChildren().at(0);    layer->setData(mode[str->getCString()]);    Director::getInstance()->pushScene(TransitionCrossFade::create(1, scene));}

The first step is strong conversion. In the callback, we use the corresponding type to strongly convert the items we create. Then, call getUserObjet of item to obtain the set value.

The next three sentences are the positive transfer value of the scenario. This will be discussed at the end of this article. The premise is to call the member functions of objects at the next scene layer to implement preaching.


**************************************** **************************************** **************************************** ***********

Switch scenario

Create a new scenario, and then use the following statement to add it to the menu callback function to switch the scenario:

   auto scene =KTWork_SwitchBg::createScene();   Director::getInstance()->replaceScene(scene);

In this way, we can switch from one scenario to another.

You can add the desired genie in another scenario. You can also try to add the scene that was created yesterday to the airplane logging scenario. Click the menu button to start hitting the plane!

 

Switch scene animation

If you want to use the switched special effect animation, modify the animation as follows:

auto scene =KTWork_SwitchBg::createScene();Director::getInstance()->replaceScene(TransitionPageTurn::create(1,scene,true));


(TransitionShrinkGrow: create (1, scene); (TransitionCrossFade: create (1, scene );

Try several special effect methods: Transition ******: create ().

 

If you want to return to the main menu, you only need to add a return button in the sub-scenario. You can think of how to return to the main menu intelligently.


If you are careful, you will be prompted for two switching modes: replacescene and pushscene. The difference between the two switching modes is that the former releases the current scenario, and the latter pushes the current scenario into the stack for storage. To switch back the pushscene scenario, you only need to call popscene in the sub-scenario. It is equivalent to suspending the original scenario for a while.

**************************************** **************************************** ****************************

Field Transfer

Forward value transfer

Before switching the scenario, we pass the parameter to the next scenario. This is the forward value.

The simplest way is to assign values to class member variables in the next scenario. In this way, we can control the attributes we want to display in the next scenario in the main scenario.

 

The following callback function is used to obtain all the subnodes in the returned scenario. Right-click the returned value of getChildren. Because there is only one node in the sub-scenario, the first element must be a layer, that is, a KTWork_PushScene class object. Then we can use tmp to transmit any forward parameters to the next scenario.

voidMenuScene::PushScene(Ref *ref){    this->stopAllActions();    auto scene =KTWork_PushScene::createScene();    <span style="color:#ff0000;">KTWork_PushScene * tmp = (KTWork_PushScene*)(scene->getChildren().at(0));</span>   Director::getInstance()->pushScene(TransitionShrinkGrow::create(1,scene));}

Note: before passing the parameter, KTWork_PushScene has already called the init () function initialization. How can we make the passed value take effect? The answer is to use the virtual function onEnter (). OnEnter is called before the scenario is displayed after the scenario is switched. So we can modify the Code as follows:

VoidHomeWork: onEnter () {<span style = "color: # ff0000;"> Layer: onEnter (); // call the onEnter method of the parent class </span> label-> setString (StringUtils: format ("% s", strHp. getCString (); // then we dynamically modify the value displayed by the Label}

In the class, we usually set the variable to private and access it through the get and set methods. In cocos2dx, there is a macro that can replace the operations that we define these two methods.

CC_SYNTHESIZE (int, hp, HP); // defines a protected variable hp, and defines two methods setHP and getHP to get and set hp values. CC_SYNTHESIZE (String, strHp, sHP); CC_SYNTHESIZE_RETAIN (_ String *, strname, Name); // This is for pointer variables. Your current usage may crash. The memory management will be detailed later. This macro definition is not as simple as you think. It reminds you to modify the class structure and destructor.

The two grandfathers must take a look at how they are defined.

 


Conclusion: we have learned about menus, touch responses, and switching scenarios. Now we can make the following game.

There are four game modes in which the sky will land in snowflakes, each of which is different in size. Click the mouse to make the snowflake hour. The game ends and returns to the main scenario.

The effect is as follows:





I put the game code on the first floor. I am also optimizing these codes later. Some knowledge points may not be involved yet. You can use the materials.

I may see the special effects of snow float and fireworks in my main scenarios. These are all implemented by copying other people's code. If you are interested, you can take a look at them, which is very simple.


Related Article

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.