2013-06-24 33 views
0

爲什麼我在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; 
} 
+3

['標準:: list'(http://en.cppreference.com/w/cpp/container/list)可能對你感興趣。 – Praetorian

+0

每個問題有一個問題,請 –

+0

第四個問題:爲什麼不使用更簡單的'GameObject'類來處理'Manager'中的錯誤? – Beta

回答

0

這是一個可怕的解決方案鏈接列表,但我會回答你的問題。該錯誤在Add()中。在這裏,您只需修改本地變量helpGameObject。相反,您應該停止在沒有後繼的對象並修改nextGameObject對象。

0

問題在於你的Add函數。

的follwing線:

helpGameObject = newGameObject; 

實際上並沒有改變指向的值helpGameObject,而它改變了指針本身。

我認爲最好的辦法是將其更改爲以下

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