横スクロール ゲームのエンティティ コンポーネント システムの作業を始めたところです。
私は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]->...
基本コンポーネント クラスの属性しか思いつきません。
どんな助けでも大歓迎です。