【问题标题】:Implementing a component System for my 2d C++ game为我的 2d C++ 游戏实现组件系统
【发布时间】:2018-01-19 10:39:50
【问题描述】:

我一直在尝试找出一种方法来为我的简单 2D 格斗游戏实现组件系统,在该系统中,我可以轻松地交换从系统函数返回的新组件。这个想法是我有一堆系统函数可以在一组组件上工作:

示例:

PosisiontComponent MovementSystem(PositionComponent pos, VelocityComponent vel)
{
    //..Make entity move
   return pos;
}

这里的关键是我想返回一个新的组件副本,而不是直接在我的系统函数中修改状态(为了更容易理解和测试系统)。理想情况下,这个新的更新位置组件可以通过某种myFighter.Insert() 成员函数插入到我的 Fighter(基本上就像一个实体类)中。到目前为止,我正在考虑使用std::map<int key, Component* comp> 来存储我的组件,键是一个唯一的 id,它只与一种组件类型连接,我可以使用它来查找地图中的某些组件。战斗机类可能看起来像:

class Fighter
{
public:
    void Insert(Component* comp);
    Component* Get();

    std::map<int, Component*> componentMap;
}

Fighter::Fighter(std::string const imageFilePath, float startPositionX, float startPositionY) :
    sprite(imageFilePath, 200, 200)
{
    componentMap[0] = new PositionComponent(glm::vec2{ 0.0f, 0.0f });
    componentMap[1] = new VelocityComponent();
}

void Fighter::Insert(Component* component)
{
    componentMap.erase(compID);
    componentMap[compID)] = component;
}

Component* GetComponent()
{
   return componentMap[id];
}

我遇到的问题是我不太清楚在当前实现中如何通过 GetComponent() 函数返回单个组件(目前由于类型转换问题而导致编译器错误)。

我的问题是:

1.) 我当前的实施方案是可行的解决方案吗?有没有办法从 GetComponent() 函数中提取特定组件而不会出现编译器问题?如果没有,有什么更好的方法可以轻松地替换我的 Fighter 类中的各个组件?

【问题讨论】:

    标签: c++ components game-engine


    【解决方案1】:

    假设每个实体的每种类型只能有一个组件,您可以使用模板。

    template<typename T>
    T* getComponent() {
        for (auto &component : components)
        {
            T* derivedComponent = dynamic_cast<T*>(component);
            if (derivedComponent)
            {
                return derivedComponent;
            }
        }
    
        return NULL;
    }
    

    然后使用它会很简单,并且不需要共享 id。地图的顺序也可以在不破坏游戏的情况下改变。这会在您在运行时添加和删除组件时发生。

    Fighter* f;
    PosisiontComponent* positionComponent = f->getComponent<PosisiontComponent>();
    

    这是我过去使用的方法,效果非常好。但是,我建议对这些容器使用智能指针而不是原始指针。

    【讨论】:

    • 感谢您的建议!让我问你,考虑到 getcomp 调用的频率,dynamic_cast 对性能的影响很大吗?
    • @Jason 是的,确实如此,动态演员阵容很多,但速度很快。它会影响性能。
    猜你喜欢
    • 2015-05-20
    • 2011-03-15
    • 1970-01-01
    • 1970-01-01
    • 2011-04-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多