Wednesday, May 6, 2015

Cocos2dx: Menus

In .h:

class HelloWorld : public cocos2d::Layer
{
public:
   
    static cocos2d::Scene* createScene();
    virtual bool init();
    
    // implement the "static create()" method manually
    CREATE_FUNC(HelloWorld);


    // The menu items:
    void Play(Ref *pSender);
    void Highscores(Ref *pSender);
    void Settings(Ref* pSender);
    void ImageButton(Ref *pSender);
   

};


Implementation:

bool HelloWorld::init()
{
    if ( !Layer::init() )
    {
        return false;
    }
    
    Size visibleSize = Director::getInstance()->getVisibleSize();
    Vec2 origin = Director::getInstance()->getVisibleOrigin();
    
    auto menu_item_1 = MenuItemFont::create("Play",
                       CC_CALLBACK_1(HelloWorld::Play, this));
    auto menu_item_2 = MenuItemFont::create("Highscores",
                       CC_CALLBACK_1(HelloWorld::Highscores, this));
    auto menu_item_3 = MenuItemFont::create("Settings",
                       CC_CALLBACK_1(HelloWorld::Settings, this));
    auto menu_item_4 = MenuItemImage::create("CloseNormal.png", "CloseSelected.png",                    
                       CC_CALLBACK_1(HelloWorld::ImageButton, this));
    
  
    auto *menu = Menu::create(menu_item_1,menu_item_2,menu_item_3,menu_item_4,NULL);
    menu->alignItemsVerticallyWithPadding(visibleSize.height/4);
    this->addChild(menu);
    
    return true;
}

void HelloWorld::Play(cocos2d::Ref *pSender){
    CCLOG("Play");
}

void HelloWorld::Highscores(cocos2d::Ref *pSender){
    CCLOG("Highscores");
}

void HelloWorld::Settings(cocos2d::Ref *pSender){
    CCLOG("Settings");
}

void HelloWorld::ImageButton(cocos2d::Ref *pSender){
    CCLOG("IMAGE BUTTON");
}


Alternatively, you can do this instead of menu->alignItemsVerticallyWithPadding(40) :


    menu_item_1->setPosition(Point(visibleSize.width/2,(visibleSize.height/5)*4));
    menu_item_2->setPosition(Point(visibleSize.width/2,(visibleSize.height/5)*3));
    menu_item_3->setPosition(Point(visibleSize.width/2,(visibleSize.height/5)*2));
    menu_item_4->setPosition(Point(visibleSize.width/2,(visibleSize.height/5)*1));

No comments:

Post a Comment