Lets create a Cocos2d-X menu with one callback method.
Overview:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
#ifndef __MAIN_LAYER_H__ #define __MAIN_LAYER_H__ #include "cocos2d.h" using namespace cocos2d; class MainLayer : public CCLayer { public: virtual bool init(); // a selector callback void menuCallback(CCObject* pSender); // will add the menu to layer, we can do it in init but this keeps things organized void createMenu(); // implement the "static node()" method manually CREATE_FUNC(MainScene); }; #endif // __MAIN_LAYER_H__ |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 |
#include "MainLayer.h" using namespace cocos2d; using namespace CocosDenshion; bool MainLayer::init() { if ( !CCLayer::init() ) { return false; } this->createMenu(); return true; } void MainLayer::createMenu(){ // create an image menu item with two images, target will be this class and callback method CCMenuItemImage *pCloseItem = CCMenuItemImage::create("CloseNormal.png","CloseSelected.png",this,menu_selector(MainLayer::menuCallback) ); //set its position somewhere pCloseItem->setPosition(200,200); //set the tag for this item, so that you will have one callback per menu and handle it accordingly pCloseItem->setTag(200); //same as first item but different tag, only for test purposes CCMenuItemImage *pItem = CCMenuItemImage::create("CloseNormal.png","CloseSelected.png",this,menu_selector(MainLayer::menuCallback) ); pItem->setPosition(400,400); pItem->setTag(100); // create menu, it's an autorelease object CCMenu* pMenu = CCMenu::create(pItem, pCloseItem, NULL); pMenu->setPosition( 0,0 ); this->addChild(pMenu, 1); } void MainLayer::menuCallback(CCObject* pSender) { CCMenuItem* pMenuItem = (CCMenuItem *)(pSender); int tag = (int)pMenuItem->getTag(); switch (tag) { case 200: CCLOG("item with i% tag selected", tag); break; case 100: CCLOG("item with i% tag selected", tag); break; } } |
Usage
1 2 3 4 |
MainLayer* layer = MainLayer::create(); //do sth with the layer |