爲什麼我在GameLoop中添加了4個GameObjects,控制檯只給出了一次「GameObject Update」和「GameObject Render」?爲什麼這個節點列表doesen't工作正確?
另一個Qustion,我怎麼能爲GameObjects做一個自毀函數?
最後一個問題,最好的方法是什麼,一個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;
}
['標準:: list'(http://en.cppreference.com/w/cpp/container/list)可能對你感興趣。 – Praetorian
每個問題有一個問題,請 –
第四個問題:爲什麼不使用更簡單的'GameObject'類來處理'Manager'中的錯誤? – Beta