Thursday, May 7, 2015

Cocos2dx: Replacing a Scene

In HelloWorld.h:

class HelloWorld : public cocos2d::Layer
{
public:
    
    static cocos2d::Scene* createScene();

    virtual bool init();
    
    CREATE_FUNC(HelloWorld);
    

    void Play(Ref *pSender);   

};


In HelloWorld.cpp:

#include "NewScene.h"
bool HelloWorld::init()
{

    if ( !Layer::init() )
    {
        return false;
    }
    
    
    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()->replaceScene(scene);
}


In NewScene.h:

class NewScene : public cocos2d::Layer
{
public:

    static cocos2d::Scene* createScene();

    virtual bool init();
    
    CREATE_FUNC(NewScene);
    
    
    void GoBack(Ref *pSender);
   
};


In NewScene.cpp:

#include "HelloWorldScene.h"
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){
    auto scene = HelloWorld::createScene();
    Director::getInstance()->replaceScene(scene);
}

No comments:

Post a Comment