2

横スクロール ゲームのエンティティ コンポーネント システムの作業を始めたところです。

私は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 

エンティティ.cpp:

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

Entity::Entity(){}

Entity::~Entity(){}

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

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

基本コンポーネント クラスの属性しか思いつきません。

どんな助けでも大歓迎です。

4

2 に答える 2

1

特定の種類のコンポーネントを特定のインデックスに格納できます。たとえば、すべての位置コンポーネントは位置 0 に保存され、すべての速度コンポーネントは位置 1 に保存されます。

その後、コンポーネントを簡単に取得できます

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

Component::getIndex() は、そのコンポーネントのインデックスを返す静的メソッドです。

于 2013-05-08T03:14:30.347 に答える
0

static_cast<T>orを使用dynamic_cast<T>して、派生クラスのメソッドにアクセスする前に、ベクター要素を適切な型にキャストします。

を使用するstatic_cast<T>には、どの要素がどのタイプであるかを覚えておく必要がありstatic_cast<T>ます。

dynamic_cast<T>が適切なポインター型でない場合は null ポインターを返しますTが、これには実行時のオーバーヘッドが伴います (これについてはあまり気にしません)。

補足として、キャストが不要になるように再設計を真剣に検討します。

于 2013-03-29T19:21:12.217 に答える