cocos2d-xでボタンを作る
ボタン機能を見てみる
- 付属しているサンプルをもとにUIのボタンを追加してみる。
- HelloWorld.cppの中を見るとこんな感じでボタンを作っている。
///////////////////////////// // 2. add a menu item with "X" image, which is clicked to quit the program // you may modify it. // add a "close" icon to exit the progress. it's an autorelease object CCMenuItemImage *pCloseItem = CCMenuItemImage::create( "CloseNormal.png", "CloseSelected.png", this, menu_selector(HelloWorld::menuCloseCallback) ); pCloseItem->setPosition( ccp(CCDirector::sharedDirector()->getWinSize().width - 20, 20) );
画面中の右下の丸いのがこのボタンで押すとmenuCloseCallbackが呼ばれてアプリが終了する。
このボタンの上に表示されるようにボタンを追加してみる。
コード追加
- 元のボタン作成コードのすぐ下で変数名、コールバック名、座標をかえたコードを入れる。
- CCMenuのオブジェクトを作ったあとにaddChildでボタンをメニューに追加する。
- CCLabelTTFで作成しているテキストラベルはあとで変更できるようにメンバ変数として保存する
- まだこの段階ではコールバック関数がなくてエラーで動かない
///////////////////////////// // 2. add a menu item with "X" image, which is clicked to quit the program // you may modify it. // add a "close" icon to exit the progress. it's an autorelease object CCMenuItemImage *pCloseItem = CCMenuItemImage::create( "CloseNormal.png", "CloseSelected.png", this, menu_selector(HelloWorld::menuCloseCallback) ); pCloseItem->setPosition( ccp(CCDirector::sharedDirector()->getWinSize().width - 20, 20) ); CCMenuItemImage *pTextChangeItem = CCMenuItemImage::create( "CloseNormal.png", "CloseSelected.png", this, menu_selector(HelloWorld::menuTextChangeCallback) ); pTextChangeItem->setPosition( ccp(CCDirector::sharedDirector()->getWinSize().width - 20, 40) ); // create menu, it's an autorelease object CCMenu* pMenu = CCMenu::create(pCloseItem, NULL); pMenu->addChild(pTextChangeItem, 1); pMenu->setPosition( CCPointZero ); this->addChild(pMenu, 1); ///////////////////////////// // 3. add your codes below... // add a label shows "Hello World" // create and initialize a label CCLabelTTF* pLabel = CCLabelTTF::create("Hello World", "Thonburi", 34); this->mLabel = pLabel;
ヘッダ編集
- ラベルを保存する変数をメンバに追加
- コールバックで呼ばれる関数を追加
class HelloWorld : public cocos2d::CCLayer { private: cocos2d::CCLabelTTF *mLabel; // ボタンを押したときにテキストを変更するラベル public: // Here's a difference. Method 'init' in cocos2d-x returns bool, instead of returning 'id' in cocos2d-iphone virtual bool init(); // there's no 'id' in cpp, so we recommand to return the exactly class pointer static cocos2d::CCScene* scene(); // a selector callback void menuCloseCallback(CCObject* pSender); // new callback function void menuTextChageCallback(CCObject *pSender); // implement the "static node()" method manually LAYER_CREATE_FUNC(HelloWorld); };
コールバック関数の実装追加
- cppにもどりコールバック関数を実装する
void HelloWorld::menuTextChangeCallback(CCObject* pSender) { this->mLabel->setString("Pressed"); }
画面
- ボタンが表示されて押すと画面上部のテキストが変わった