【问题标题】:SFML2 Collision with every objectSFML2 与每个对象的碰撞
【发布时间】:2014-05-15 18:40:12
【问题描述】:

我是 SFML 的初学者,我想了解碰撞。我制作了游戏类、实体类和实体管理器来保持正确,我制作了一个碰撞函数来检测 2 个对象之间的碰撞,但我的问题是:如何检查场景中每个对象的碰撞?我的意思是..我有一个派生自 Entity 的 Player 类,我想测试它是否与场景中的每个实体(但不是 Player)对象发生碰撞,你能帮帮我吗?

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

游戏.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

我希望有人能理解我的意思并给出一些建议或例子..

【问题讨论】:

    标签: c++ collision-detection game-engine sfml


    【解决方案1】:

    您可以做的是遍历所有实体并检查它是否不是玩家,然后检查是否存在碰撞。

    我猜你是在 Game 类的某个地方创建 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 和 clang,自 VS2012 起默认支持):

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

    另一个想法是在您的碰撞函数中验证作为参数传递的两个实体不具有相同的地址(作为不同的对象)。

    【讨论】:

    • 非常感谢!从第一次尝试开始!
    猜你喜欢
    • 2015-08-07
    • 1970-01-01
    • 2017-09-25
    • 2023-02-25
    • 2013-02-26
    • 2013-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多