【问题标题】:How to access properties from subclasses in an entity component system如何从实体组件系统中的子类访问属性
【发布时间】:2013-03-29 19:08:25
【问题描述】:

我刚刚开始为横向卷轴游戏开发实体组件系统。

我对 C++ 很陌生,但我已经阅读了很多教程,并决定最好的方法是拥有一个包含组件向量的实体类。然后会有一个基础组件类实际上组件作为子类。

Entity.h:

#ifndef _ENTITY_H
#define _ENTITY_H

#include "header.h"

class Entity

{

public:
    Entity();
    ~Entity();

    // Vector which stores all added components
    vector<Component*> Components;

    // Add component method
    void AddComponent(Component* component);

};

#endif 

Entity.cpp:

#include "header.h"
#include "Component.h"
#include "Entity.h"

Entity::Entity(){}

Entity::~Entity(){}

void Entity::AddComponent(Component* component)
{
    Components.push_back(component);
}

组件.h:

#ifndef _COMPONENT_H
#define _COMPONENT_H

#include "header.h"


class Component

{

public:

    // Forward declaration 
    class Entity;

    Component();
    ~Component();

    void Connect(Entity* entity) {}

    string Name;
};


// Position component
class Position: public Component{ 

public:
    int x, y; 

};

// Display component
class Display: public Component{ 

public:

    sf::Sprite baseSprite; };

#endif

组件.cpp:

#include "header.h"
#include "Component.h"

Component::Component(){}

Component::~Component(){}

现在要添加一个新组件,我会这样做:

Entity* new_component;
new_component = new Entity;
new_component->AddComponent(new Position);  
new_component->AddComponent(new Display);   

问题是,我不知道如何在添加组件后再次实际访问它。

例如,我希望能够访问 Position 的 x 和 y 值。但是当我尝试像这样访问列表中的组件时:

Components[i]->...

我只是想出了基础组件类的属性。

任何帮助将不胜感激。

【问题讨论】:

    标签: c++ components system entities subclass


    【解决方案1】:

    您可以将某些类型的组件存储在某个索引中。 例如,所有位置分量都存储在位置 0,所有速度分量都存储在位置 1。

    然后你就可以轻松检索组件了

    template <class T>
    T * Entity::getComponent()
    {
        return static_cast<T*>(components[T::getIndex()]);
    }
    

    Component::getIndex() 是一个静态方法,应该返回该组件的索引。

    【讨论】:

      【解决方案2】:

      在访问派生类的方法之前,使用static_cast&lt;T&gt;dynamic_cast&lt;T&gt; 将向量元素转换为适当的类型。

      要使用static_cast&lt;T&gt;,您必须记住哪个元素属于哪个类型,因为static_cast&lt;T&gt; 不会告诉您。

      如果T 不是适当的指针类型,dynamic_cast&lt;T&gt; 将返回一个空指针,但这会带来一些运行时开销(我不会太担心)。

      作为旁注,我会认真考虑重新设计,这样就不需要铸造了。

      【讨论】:

      • 啊,有道理。你知道我可以看的不涉及铸造的好设计的任何例子吗?由于我是 C++ 新手,刚开始玩这个游戏,我真的很想让事情尽可能简单。谢谢!
      猜你喜欢
      • 2020-09-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-07
      • 1970-01-01
      • 2020-02-25
      • 2020-07-14
      • 2019-05-29
      相关资源
      最近更新 更多