关于Cocos2d-x中UI按钮的定义
1.要有两张不同状态的图片
2.定义一个MenuItemSprite的实例,把这两张图的Sprite实例放进MenuItemSprite的实例
3.把MenuItemSprite的实例放进Menu实例
(4.暂停按钮的这种的要把MenuItemSprite的实例再放进MenuItemToggle实例中,再把MenuItemToggle实例放进Menu实例中)
5.把Menu实例addChild到层
例子
开始游戏按钮
1 auto startNormal = Sprite::create("startNormal.png"); 2 auto startSelected = Sprite::create("startSelected.png"); 3 auto startSpriteItem = MenuItemSprite::create(startNormal, startSelected, CC_CALLBACK_1(StartUp::menuStartCallback, this)); 4 auto menu = Menu::create(startSpriteItem, NULL); 5 this->addChild(menu); 6 menu->setPosition(visibleSize.width / 2, visibleSize.height / 2);
1 void StartUp::menuStartCallback(Ref* pSender) 2 { 3 //Director::getInstance()->getEventDispatcher()->removeEventListener(touchListener); 4 Director::getInstance()->replaceScene(TransitionFade::create(1, GameScene::createScene(1))); 5 }
暂停按钮
1 //加入暂停按钮 2 auto pause_sp1 = Sprite::create("game_pause_nor.png"); 3 auto pause_sp2 = Sprite::create("game_pause_pressed.png"); 4 auto resume_sp1 = Sprite::create("game_resume_nor.png"); 5 auto resume_sp2 = Sprite::create("game_resume_pressed.png"); 6 7 auto pauseitem = MenuItemSprite::create(pause_sp1, pause_sp2); 8 auto resumeitem = MenuItemSprite::create(resume_sp1, resume_sp2); 9 auto pauseButton = MenuItemToggle::createWithTarget(this, menu_selector(GameScene::pauseButtonCallBack), pauseitem, resumeitem, nullptr); 10 pauseButton->setAnchorPoint(Vec2(0, 0)); 11 pauseButton->setPosition(Vec2(size.width / 2 - pauseButton->getContentSize().width, size.height / 2 - pauseButton->getContentSize().height)); //位于左上角 12 13 auto menu = Menu::create(pauseButton, nullptr); 14 menu->setScale(0.2); 15 addChild(menu, 4, PAUSE_MENU);
1 void GameScene::pauseButtonCallBack(Ref* pSender) 2 { 3 //log("press pause button!"); 4 }