我正在为使用可变参数模板构建游戏对象的 2D 游戏引擎编写实体组件系统。这是对象类,它只是所有组件的容器。我删除了不相关的东西。
template<class ... Components>
class Object : public Components...{
public:
Object(Game* game) : Components(game)...{
}
};
组件由对象继承,但我试图找到检查这些组件类型的最佳方法,以便它们可以正确地相互通信。例如,物理组件将包含对象的更新位置。 Drawable 组件需要获得该位置,以便它可以绘制在世界上的正确位置。我想向 Object 添加一个更新功能,以更新每个组件并传输任何可以/需要在当前组件之间传输的信息。
最佳答案
多态性就是你想要的。 只需像这样制作所有组件:
public Object
{
enum TYPE{
COMPONENT,,
GAMEOBJECT,
ETC,,,
};
Object(TYPE id){m_id = id;}
protected:
TYPE m_id;
virtual void Update(void) = 0;
virtual void Render(void) = 0;
public:
void GetTypeOf(void)const{return m_id;}
};
class Component : Object
{
enum COMPONENT_TYPE
{
COLLIDER,
RENDERER,
ETC,,,,
};
Component() : Object (COMPONENT){/**/}
virtual void Update(void){return;}
virtual void Render(void){return;}
};
class BoxCollider : Component
{
BoxCollider(void) : Component(BOXCOLLIDER){/**/}
void Update(void)
{
//to do
}
void Render(void)
{
//to do
}
};
那么你可以简单地拥有一个 Object* 或 Component* 的数据结构 你可以通过这种方式迭代:
std::vector<Component*>::iterator components = ComponentVector.begin();
for(;components != ComponentVector.end() ; ++components)
{
*(component)->Update();
*(component)->Render();
std::cout << "id" << *component->getTypeOf() << std::endl;
}
关于c++ - 动态检查使用可变参数继承的类的类型的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28415725/