http://download.csdn.net/detail/yincheng01/6864893
解压密码:c.itcast.cn
上一篇博文提到appDelegate,在该类的重载函数applicationDidFinishLaunching函数中,程序进入CMMenuScene场景,我们顺藤摸瓜来学习CMMenuScene。
class CMMenuScene : public cocos2d::CCLayerColor { private: bool m_bIsBtnClicked; //是否点击上按钮 public: static CCScene* CreateMenuScene(); //触摸函数 virtual bool ccTouchBegan(CCTouch *pTouch, CCEvent *pEvent); virtual void ccTouchMoved(CCTouch *pTouch, CCEvent *pEvent); virtual void ccTouchEnded(CCTouch *pTouch, CCEvent *pEvent); protected: virtual bool init(); CREATE_FUNC(CMMenuScene); virtual void onEnter(); virtual void onExit(); //按钮回调:开始游戏 void OnStartCallBack(CCObject *pSender); //按钮回调:退出游戏 void OnQuitCallBack(CCObject *pSender); //按钮回调:关于 void OnAboutCallBack(CCObject *pSender); protected: //标签 enum { enTagMenu=100, }; };
bool CMMenuScene::init() { do { CC_BREAK_IF(CCLayerColor::initWithColor(ccc4(0,50,0,50))==false); //CC_BREAK_IF(CCLayerColor::initWithColor(ccc4(255,0,0,255))==false); m_bIsBtnClicked = false; //添加背景 CCSprite* pPauseLayerBG = CCSprite::create("menuscene/background.png"); CC_BREAK_IF(pPauseLayerBG==NULL); pPauseLayerBG->setPosition(ccp(SCREEN_WIDTH/2,SCREEN_HEIGHT/2 + 58)); this->addChild(pPauseLayerBG,enZOrderMiddle); //添加菜单 CCMenu * pMenu = CCMenu::create(); CC_BREAK_IF(pMenu==NULL); pMenu->setPosition(CCPointZero); this->addChild(pMenu,enZOrderFront,enTagMenu); //添加按钮 CCMenuItemImage * pStartButton = CCMenuItemImage::create("menuscene/startgame_normal.png","menuscene/startgame_select.png",this,menu_selector(CMMenuScene::OnStartCallBack)); CC_BREAK_IF(pStartButton==NULL); pStartButton->setPosition(ccp(SCREEN_WIDTH/2,SCREEN_HEIGHT/2 - 28)); pMenu->addChild(pStartButton,enZOrderFront); //添加按钮 CCMenuItemImage * pQuitButton = CCMenuItemImage::create("menuscene/quitgame_normal.png","menuscene/quitgame_select.png",this,menu_selector(CMMenuScene::OnQuitCallBack)); CC_BREAK_IF(pQuitButton==NULL); pQuitButton->setPosition(ccp(SCREEN_WIDTH/2,SCREEN_HEIGHT/2 - 78)); pMenu->addChild(pQuitButton,enZOrderFront); //添加按钮 CCMenuItemImage * pAboutButton = CCMenuItemImage::create("menuscene/about_normal.png","menuscene/about_select.png",this,menu_selector(CMMenuScene::OnAboutCallBack)); CC_BREAK_IF(pAboutButton==NULL); pAboutButton->setPosition(ccp(SCREEN_WIDTH - 50,20)); pMenu->addChild(pAboutButton,enZOrderFront); return true; } while (false); CCLog("Fun CSMMenuSceneLayer::init Error!"); return false; }
在init函数里并没有启用触摸,所以,触摸函数并不会被调用。
这里的结构是,CMMenuScene -> CCMenu -> CCMenuItem,CCMenuItem控件的位置
是由CCMenuItem的setPosition来定位的,但是事实上也也已通过pMenu->alignItemsVertically来让控件对齐。
关注pStartButton,这个是开始游戏按钮,点击开始游戏,那么程序切换到游戏场景。
void CMMenuScene::OnStartCallBack( CCObject *pSender ) { CCDirector* pDirector = CCDirector::sharedDirector(); CCScene *pScene = CMGameScene::CreateGameScene(); pDirector->replaceScene(pScene); }
切换场景是由导演类来发起的,通过导演雷的replaceScene将新的场景,覆盖旧的场景。
切换场景可以有切换动画,切换动画见特别专题。