Cococs2d-x学习笔记
场景与层的关系
一个场景(Scene)有n个层(Layer)对应,并且层的个数至少为1。
场景切换
场景切换相关函数
void runWithScene(Scene * scene)
:该函数可以运行场景,只能在启动第一个创景时调用该函数,如果已经有一个场景运行情况下则不能调用该函数。void replaceScene(Scene * scene)
:切换到下一个场景,用一个新的场景替换当前场景,当前场景被终端释放。void pushScene(Scene * scene)
:切换到下一个场景,将当前场景挂起放入场景堆栈中,然后再切换到下一个场景中。void popScene()
:与pushScene
配合使用,可以回到上一个场景。void popToRootScene()
:与pushScene
配合使用,可以回到根场景。
注意:replaceScene
会释放和销毁场景,pushScene
并不会释放和销毁场景,原来场景的状态可以保持。
使用replaceScene
代码如下:
auto sc = Setting::createScene(); Director::getInstance()->replaceScene(sc);
使用pushScene
代码如下:
auto sc = Setting::createScene(); DIrector::getInstance()->pushScene(sc);
实例
首先需要在VS2015中添加一个Setting场景(即创建一个头文件和CPP文件),根据我的尝试,应该是放在classes文件夹下。
HelloWorld.h文件
#ifndef __HELLOWORLD_SCENE_H__
#define __HELLOWORLD_SCENE_H__
#include "cocos2d.h"
#include "SettingScene.h"
class HelloWorld : public cocos2d::Layer
{
public:
static cocos2d::Scene* createScene();
virtual bool init();
// a selector callback
void menuItemStartCallback(Ref * pSender);
void menuItemSettingCallback(Ref * pSender);
void menuItemHelpCallback(Ref * pSender);
// implement the "static create()" method manually
CREATE_FUNC(HelloWorld);
};
#endif // __HELLOWORLD_SCENE_H__
HelloWorld.cpp文件
#include "HelloWorldScene.h"
USING_NS_CC;
Scene* HelloWorld::createScene()
{
// 'scene' is an autorelease object
auto scene = Scene::create();
// 'layer' is an autorelease object
auto layer = HelloWorld::create();
// add layer as a child to scene
scene->addChild(layer);
// return the scene
return scene;
}
// on "init" you need to initialize your instance
bool HelloWorld::init()
{