用C ++实现替换游戏场景

时间:2013-11-08 22:43:26

标签: c++ scene

我的C ++游戏中有大约10个场景类。它类似于常规游戏屏幕(菜单屏幕,游戏屏幕,排行榜,选项等)。所以我需要一些技术来将一个场景替换为另一个场景。我已经阅读了您在此主题中发布的所有评论并试图实现它。现在我有以下代码:

// -----[ main.cpp ]----- //
#include "SceneManager.h"
#include "Scene.h"

int main( int argc, const char * argv[] ) {
    SceneManager *sceneManager = new SceneManager();
    sceneManager->changeScene( 0 );
    delete sceneManager;
    return 0;   
}

// -----[ Scene.h ]----- //
class SceneManager;
class Scene {
public:
    SceneManager *sceneManager;
    void start( SceneManager *sceneManager );
};

// -----[ SceneManager.h ]----- //
#include "Scene.h"
#include "MenuScene.h"
#include "GameScene.h"

class Scene;
class MenuScene;
class GameScene;

class SceneManager {
public:
    Scene* scene;

    void changeScene( short id ) {

        if ( scene != NULL ) {
            delete scene; // to prevent a memory leak
        }

        if ( id == 0 ) {
            scene = new MenuScene();
        } else if ( id == 1 ) {
            scene = new GameScene();
        }

        if (scene) {
            scene->start( this );
        }
    }
};


// -----[ MenuScene.h ]----- //
class MenuScene: public Scene {
public:
    void start( SceneManager *sceneManager ) {
        this->sceneManager = sceneManager;
    }
};

// -----[ GameScene.h ]----- //
class GameScene: public Scene {
public:
    void start( SceneManager *sceneManager ) {
        this->sceneManager = sceneManager;
    }
};

由于错误(XCode 4.6,MacOS X)而无法正常工作:

Apple Match-O Linker (id) Error
Undefined symbols for architecture x86_64:
  "Scene::start(SceneManager*)", referenced from:
      SceneManager::changeScene(short) in main.o
ld: symbol(s) not found for architecture x86_64

我做错了什么?怎么解决?也许有人知道关于这个主题的一些热门问题?

1 个答案:

答案 0 :(得分:1)

正如评论中所提到的,我相信你的设计在概念上需要另一个课程。这是一个粗略的例子。

class Scene {
public:
    virtual void start() = 0;
};

class SceneManager {
public:
    void changeScene( short id ) {

        Scene* scene = NULL;
        if ( id == 0 ) {
            scene = new MenuScene(); // undeclared yet
        } else if ( id == 1 ) {
            scene = new GameScene(); // undeclared yet
        }

        if (scene) {
            // TODO: make the scene visible.
            scene->start();
        }
    }
};

class MenuScene: public Scene {
public:
    virtual void start() {
        // Draw menu stuff
    }
};

class GameScene: public Scene {
public:
    void start() {
        // Draw game stuff
    }
};

如果不了解有关特定环境的更多背景信息,那么很难具体而言。