为什么,虽然我添加了 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;
}