2

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

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

实体.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 

实体.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]->...

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

Any help would be much appreciated.

4

2 回答 2

1

You can store certain types of components in a certain index. For example, all position components are stored in position 0, all velocity components are stored in position 1.

Then you can retrieve the components easily

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

Component::getIndex() is a static method that should return the index for that component.

于 2013-05-08T03:14:30.347 回答
0

Use static_cast<T> or dynamic_cast<T> to cast the vector element to the appropriate type before accessing methods of the derived class.

To use static_cast<T>, you will have to remember which element is of which type, because the static_cast<T> will not tell you.

dynamic_cast<T> will return a null-pointer if T is not of the appropriate pointer type, but this entails some run time overhead (about which I wouldn't be too concerned).

As a side note, I would seriously consider a redesign so that casting is not necessary.

于 2013-03-29T19:21:12.217 回答