Thursday, May 7, 2015

Cocos2dx: Pushing and Popping Scenes

In HelloWorld.h:

//The default scene
class HelloWorld : public cocos2d::Layer
{
public:
    
    static cocos2d::Scene* createScene();
   
    virtual bool init();
    

    CREATE_FUNC(HelloWorld);
     
    //Play button will push  NewScene to the stack
    void Play(Ref *pSender);
   

};


In HelloWorld.cpp:
#include "NewScene.h"

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 = Menu::create(menu_item_1,NULL);
    menu->alignItemsVerticallyWithPadding(40);
    this->addChild(menu);
    
    return true;
}

void HelloWorld::Play(cocos2d::Ref *pSender){
    CCLOG("Play");
    auto scene = NewScene::createScene();
    Director::getInstance()->pushScene(scene);
}


In NewScene.h:

//The scene that is pushed onto the stack
class NewScene : public cocos2d::Layer
{
public:
    
    static cocos2d::Scene* createScene();
    virtual bool init();

    CREATE_FUNC(NewScene);
 
   //GoBack button will pop this scene from the top of the stack
   void GoBack(Ref *pSender);
   
};

In NewScene.cpp:

bool NewScene::init()
{
   
    if ( !Layer::init() )
    {
        return false;
    }
    

    auto menu_item_1 = MenuItemFont::create("Go Back", CC_CALLBACK_1(NewScene::GoBack, this));
   
    auto *menu = Menu::create(menu_item_1,NULL);
    menu->alignItemsVerticallyWithPadding(40);
    this->addChild(menu);
   
    
    return true;
}

void NewScene::GoBack(cocos2d::Ref *pSender){
    Director::getInstance()->popScene();
}

No comments:

Post a Comment