Cocos2d-x3.2场景切换

//GameScene.h
#include "cocos2d.h"

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

    virtual bool init();

    void menuCallback(cocos2d::Ref* pSender);
    
    CREATE_FUNC(GameScene);
};

//GameScene.cpp
#include "GameScene.h"
#include "HelloWorldScene.h"
USING_NS_CC;

cocos2d::Scene* GameScene::createScene()
{
    auto scene = Scene::create();   //创建一个场景
    auto layer = GameScene::create();   //创建一个图层
    scene->addChild(layer);
    return scene;
}

//初始化当前的图层
bool GameScene::init()
{
    if(!Layer::init())      //初始化父类
        return false;
    
    //添加一个图片精灵
    Size visibleSize = Director::getInstance()->getVisibleSize();   //获取屏幕大小
    auto sprite1 = Sprite::create("game.png");
    sprite1->setAnchorPoint(Point::ZERO);    //设置锚点在左下角,原锚点位置在中心
    sprite1->setPosition(Point(0,0));
    //sprite1->setPosition(Point(visibleSize.width/2, visibleSize.height/2));
    this->addChild(sprite1);
    
     //添加一个菜单层,当点击按钮时调用menuCallback方法
    auto backItem = MenuItemImage::create(
                                           "CloseNormal.png",
                                           "CloseSelected.png",
                                           CC_CALLBACK_1(GameScene::menuCallback, this));
	backItem->setPosition(Point(visibleSize.width-50, 50));
    
    auto menu = Menu::create(backItem, NULL);
    menu->setPosition(Point::ZERO);
    this->addChild(menu, 1);
    
    return true;
}

//从游戏场景跳转到Hello场景
void GameScene::menuCallback(cocos2d::Ref* pSender)
{
    //方法一
//    auto scene = HelloWorld::createScene();     //创建一个新场景,因为原场景已删除
//    Director::getInstance()->replaceScene(scene);
    //方法二
    Director::getInstance()->popScene();        //原场景依然存在,直接出栈
}


你可能感兴趣的:(Cocos2d-x3.2场景切换)