이전게시판/cocos-2d

Cocos2dx Change Scene 화면전환 예제

ㅇㅇㅇㅇㅇㅇㅇㅇㅇㅇㅇㅇㅇ 2025. 1. 2. 14:31

Cocos2dx Change Scene 화면전환 예제

replaceScene: 화면이 전환될 때 메모리를 해제한다. 메모리가 해제되긴 하지만 메모리를 해제해서 이전 상태값 저장이 되지 않는다.

HelloWorldScene.h

#ifndef __HELLOWORLD_SCENE_H__
#define __HELLOWORLD_SCENE_H__

#include "cocos2d.h"

USING_NS_CC;


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

    void changeScene(Ref* sender);
};

#endif // __HELLOWORLD_SCENE_H__

HelloWorld.cpp

#include "HelloWorldScene.h"
#include "SimpleAudioEngine.h"
#include "GameScene.h"

USING_NS_CC;

Scene* HelloWorld::createScene()
{
    auto scene = Scene::create();

    auto layer = HelloWorld::create();
    scene->addChild(layer);

    return scene;
}

// on "init" you need to initialize your instance
bool HelloWorld::init()
{
    if (!LayerColor::initWithColor(Color4B(0, 0, 255, 255))) {
        return false;
    }

    auto item = MenuItemFont::create("Game Scene", CC_CALLBACK_1(HelloWorld::changeScene, this));

    auto menu = Menu::create(item, NULL);
    menu->alignItemsHorizontally();
    this->addChild(menu);
   
    return true;
}

void HelloWorld::changeScene(Ref* sender) {
    Director::getInstance()->replaceScene(GameScene::createScene());
}

GameScene.h

#ifndef __OTHER_SCENE_H__
#define __OTHER_SCENE_H__

#include "cocos2d.h"

USING_NS_CC;

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

	virtual bool init();
	CREATE_FUNC(GameScene);
};

#endif

GameScene.cpp

#include "GameScene.h"

Scene* GameScene::createScene() {
	auto scene = Scene::create();

	auto layer = GameScene::create();
	scene->addChild(layer);

	return scene;
}

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

	return true;
}