Then describe the basic knowledge of Cocos2D-x. This section describes the definition and response of the Cocos2D-x menu.
Let's start with the code. We can directly debug the changes in the init function of helloworld:
Bool HelloWorld: init ()
{
Bool bRet = false;
Do
{
//////////////////////////////////////// //////////////////////////////////
// Super init first
//////////////////////////////////////// //////////////////////////////////
CC_BREAK_IF (! CCLayer: init ());
//////////////////////////////////////// //////////////////////////////////
CCSize size = CCDirector: shareddire()-> getWinSize ();
CCMenuItemImage * pCloseItem = CCMenuItemImage: create ("CloseNormal.png", "CloseSelected.png", this, menu_selector (HelloWorld: menuCloseCallback ));
CC_BREAK_IF (! PCloseItem );
// Place the menu item bottom-right conner.
PCloseItem-> setPosition (ccp (CCDirector: shareddire()-> getWinSize (). width-20, 20 ));
CCLabelTTF * label = CCLabelTTF: create ("Show Sprite", "Arial", 30 );
CCMenuItemLabel * plabel = CCMenuItemLabel: create (label, this, menu_selector (HelloWorld: LabelCallback ));
// Create a menu with the "close" menu item, it's an auto release object.
CCMenu * pMenu = CCMenu: create (pCloseItem, plabel, NULL );
PMenu-> setPosition (size. width/2, size. height/2 );
CC_BREAK_IF (! PMenu );
PMenu-> alignItemsVertically ();
// Add the menu to HelloWorld layer as a child layer.
This-> addChild (pMenu, 2 );
CCSprite * pSprite = CCSprite: create ("HelloWorld.png ");
CC_BREAK_IF (! PSprite );
PSprite-> setPosition (ccp (size. width/2, size. height/2 ));
PSprite-> setVisible (false );
This-> addChild (pSprite, 0, 1 );
BRet = true;
} While (0 );
Return bRet;
}
Void HelloWorld: menuCloseCallback (CCObject * pSender)
{
// "Close" menu item clicked
CCDirector: sharedDirector ()-> end ();
}
Void HelloWorld: LabelCallback (CCObject * pSender)
{
CCSprite * spr = (CCSprite *) this-> getChildByTag (1 );
If (spr-> isVisible ())
{
Spr-> setVisible (false );
}
Else
Spr-> setVisible (true );
}
The following code is explained:
First, the menu item: CCMenuItem has many forms of implementation. Here we use the most common MenuItemImag and MenuItemLabel. For details, see the documentation.
CmenuItem needs to be added to the container CCMenu for use (in fact, the CCMenu here is like CCsene I only understand) and then added CCMenu to the Layer to display it in the scene.
Note that menu_selector () is used to set menu events.
Demo Source: http://download.csdn.net/detail/vanquishedzxl/7047123