2014-04-03 78 views
1

我是一個初學SFML,我想了解碰撞..我讓遊戲類,實體類和一個實體管理器保持正確,我做了一個碰撞函數檢測兩個物體之間的碰撞,但我的問題是:如何檢查場景中每個物體的碰撞?我的意思是..我有一個從實體派生的Player類,我想測試它是否與場景中的每個對象都是實體而不是玩家碰撞,你能幫助我嗎?SFML2碰撞每個對象

Entity.h

#ifndef ENTITY_H_INCLUDED 
#define ENTITY_H_INCLUDED 
class Entity { 
    public: 
     Entity(); 
     ~Entity(); 
     virtual void Draw(sf::RenderWindow& mWindow); 
     virtual void Update(); 
     virtual void Load(std::string file); 
     virtual sf::Sprite GetEntity(); 
     bool IsLoaded(); 
     bool mIsLoaded; 
     std::string mFile; 
     sf::Texture mTexture; 
     sf::Sprite mSprite; 
}; 
#endif 

EntityManager.h

#ifndef ENTITYMANAGER_H_INCLUDED 
#define ENTITYMANAGER_H_INCLUDED 
#include "Entity.h" 
class EntityManager { 
    public: 
     void Add(std::string name, Entity* entity); 
     void Remove(std::string name); 
     Entity* Get(std::string name) const; 
     int GetEntityCount() const; 
     void DrawAll(sf::RenderWindow& mWindow); 
     void UpdateAll(); 

    private: 
     std::map <std::string, Entity*> mEntityContainer; 
}; 
#endif 

PlayerPlane.h

#ifndef PLAYERPLANE_H_INCLUDED 
#define PLAYERPLANE_H_INCLUDED 
#include "Entity.h" 
class PlayerPlane : public Entity { 
    public: 
     PlayerPlane(); 
     ~PlayerPlane(); 
     void Update(); 
     void Draw(sf::RenderWindow& mWindow); 
}; 
#endif 

Game.h

#ifndef GAME_H_INCLUDED 
#define GAME_H_INCLUDED 
#include "EntityManager.h" 

class Game { 
    public: 
     static void Run(); 
     static void GameLoop(); 

    private: 
     static sf::RenderWindow mWindow; 
     static EntityManager mEntityManager; 
}; 
#endif 

我希望有人會明白我的意思,並給出一些建議或例子。

回答

1

你可以做的是循環所有你的實體,並檢查它不是玩家,然後檢查是否有碰撞。

我想你是在你的遊戲類的某處創建了你的PlayerPlane對象,那麼你應該保存一個指針,因爲它是你遊戲中的一個特殊實體。

然後,你可以做你的GameLoop:

for (std::<std::string, Entity*>::iterator it = mEntityContainer.begin(); it != mEntityContainer.end(); ++it) 
{ 
    if (it->second != pointerToPlayer) 
    { 
     checkCollision(it->second, pointerToPlayer); 
    } 
} 

或者,更簡潔的C++ 11(-std=c+11 GCC和鏗鏘,因爲VS2012默認支持的):

for (const auto& entity : mEntityContainer) 
{ 
    if (entity.second != pointerToPlayer) 
    { 
     checkCollision(it.second, pointerToPlayer); 
    } 
} 

另一個想法是在碰撞函數中驗證作爲參數傳遞的兩個實體不具有相同的地址(是不同的對象)。

+0

非常感謝!從第一次嘗試! –