0

为什么,虽然我添加了 4 个游戏对象,但在 GameLoop 控制台中只给出了一次“游戏对象更新”和“游戏对象渲染”?

还有另一个 Qustion,我如何为游戏对象创建一个自毁功能?

最后一个问题是,GameObject 可以与列表中的其他游戏对象进行通信的最佳方法是什么?

#include <iostream>
using namespace std;

class GameObject
{
public:
    GameObject *nextGameObject;

    GameObject()
    {
        cout<<"GameObject Constructor!\n";
        nextGameObject = nullptr;
    }
    ~GameObject()
    {
        cout<<"GameObject Destructor\n";
        if(nextGameObject != nullptr)
        {
            delete nextGameObject;
        }
    }

    virtual void Update()
    {
        cout<<"GameObject Update!\n";
    }
    virtual void Render()
    {
        cout<<"GameObject Render!\n";
    }
};

class GameObjectManager
{
private:
    GameObject *firstGameObject;
public:
    GameObjectManager()
    {
        firstGameObject = nullptr;
    }
    ~GameObjectManager()
    {
        if(firstGameObject != nullptr)
        {
            delete firstGameObject;
        }
    }

    void Update()
    {
        if(firstGameObject != nullptr)
        {
            GameObject *helpGameObject = firstGameObject;
            while(helpGameObject != nullptr)
            {
                helpGameObject->Update();
                helpGameObject = helpGameObject->nextGameObject;
            }
        }
    }
    void Render()
    {
        if(firstGameObject != nullptr)
        {
            GameObject *helpGameObject = firstGameObject;
            while(helpGameObject != nullptr)
            {
                helpGameObject->Render();
                helpGameObject = helpGameObject->nextGameObject;
            }
        }
    }

    void Add(GameObject *newGameObject)
    {
        if(firstGameObject == nullptr)
        {
            firstGameObject = newGameObject;
        }
        else
        {
            GameObject *helpGameObject = firstGameObject;
            while(helpGameObject != nullptr)
            {
                helpGameObject = helpGameObject->nextGameObject;
            }
            helpGameObject = newGameObject;
        }
    }
};

int main()
{
    GameObjectManager gom;
    bool run = true;

    gom.Add(new GameObject);
    gom.Add(new GameObject);
    gom.Add(new GameObject);
    gom.Add(new GameObject);

    while(run)
    {
        cout<<"GameLoop Start\n";
        gom.Update();
        gom.Render();
        cout<<"GameLoop End\n";
        cin.get();
    }

    return 0;
}
4

2 回答 2

0

对于链表来说,这是一个可怕的解决方案,但我会回答你的问题。错误在 Add() 中。在这里,您只需修改局部变量 helpGameObject。相反,您应该在没有后继对象的对象处停止并修改该对象 nextGameObject。

于 2013-06-24T18:35:56.953 回答
0

问题出在你的Add功能上。

以下行:

helpGameObject = newGameObject;

实际上并没有改变 指向的值helpGameObject,而是改变了指针本身。

我认为最好的解决方案是将其更改为以下

        GameObject *helpGameObject = firstGameObject;
        while(helpGameObject->nextGameObject != nullptr)
        {
            helpGameObject = helpGameObject->nextGameObject;
        }
        helpGameObject->nextGameObject = newGameObject;
于 2013-06-24T18:36:16.460 回答