We are all probably familiar with what a menu is. We see these in every application we use. In your game you would probably use a Menu object to navigate through game options. Menus often contain buttons like Play, Quit, Settings and About, but could also contain other Menu objects for a nested menu system. A Menu object is a special type of Node object. You can create an empty Menu object as a place holder for your menu items:

auto myMenu = Menu::create();

As we described options above of Play, Quit, Settings and About, these are your menu items. A Menu without menu items makes little sense. Cocos2d-x offers a variety of ways to create your menu items including by using a Label object or specifying an image to display. Menu items usually have two possible states, a normal and a selected state. When you tap or click on the menu item a callback is triggered. You can think of this as a chain reaction. You tap/click the menu item and it runs the code you specified. A Menu can have just a single item or many items.

// creating a menu with a single item

// create a menu item by specifying images
auto closeItem = MenuItemImage::create("CloseNormal.png", "CloseSelected.png",
CC_CALLBACK_1(HelloWorld::menuCloseCallback, this));

auto menu = Menu::create(closeItem, NULL);
this->addChild(menu, 1);

A menu can also be created by using a vector of MenuItem objects:

// creating a Menu from a Vector of items
Vector<MenuItem*> MenuItems;

auto closeItem = MenuItemImage::create("CloseNormal.png", "CloseSelected.png",
CC_CALLBACK_1(HelloWorld::menuCloseCallback, this));


/* repeat for as many menu items as needed */

auto menu = Menu::createWithArray(MenuItems);
this->addChild(menu, 1);

If you run the sample code for this chapter you will see a Menu containing Label objects for MenuItems:

Lambda functions as Menu callbacks

Above we just learned that when you click a menu item it triggers a callback. C++11 offers lambda functions and therefore Cocos2d-x takes full advantage of them! A lambda function is a function you write inline in your source code. Lambdas are also evaluated at runtime instead of compile time.

A simple lambda:

// create a simple Hello World lambda
auto func = [] () { cout << "Hello World"; };

// now call it someplace in code

Using a lambda as a MenuItem callback:

auto closeItem = MenuItemImage::create("CloseNormal.png", "CloseSelected.png",
[&](Ref* sender){
    // your code here

results matching ""

    No results matching ""