我的想法: 我希望能够使用作为参数传入的组件的副本创建新实体,还可以对未定义数量的组件使用可变参数模板函数。
原因:我想要一种在运行时创建新实体的简单方法。
问题:我的初始代码没有创建组件的副本,而是使用引用并将指针保存在组件数组中。就我目前的知识而言,所需的代码对我来说有点太复杂了。帮助表示赞赏。
理想代码:
//Creating components
TransformComponent a;
a.SetPosition(50, 50);
RenderComponent b;
b.SetColor(0.5f, 0.5f, 0.0f, 1.0f);
//Creating entities
EntityHandle entity1 = CreateEntity(a, b, ...); //Undefined amount of components
//Assign new values
a.SetPosition(100,100);
b.SetColor(0.5f, 0.5f, 0.0f, 1.0f);
EntityHandle entity2 = CreateEntity(a, b, ...);
//New entity has a copy of the same components
//used when creating the first entity,
//without changing the values of the first entity
到目前为止我的尝试:(在传递组件引用时有效)
TransformComponent tTest;
tTest.transform.SetPosition(200.f, 200.f);
RenderComponent rTest;
rTest.texture = &texture;
ecs.CreateEntity(&tTest, &rTest);
//Creating an entity with undefined number of arguments
template <class... Component>
EntityHandle CreateEntity(Component*... componets)
{
EntityHandle newEntity = CreateEntity();
AddComponent(newEntity, componets...);
return newEntity;
}
void DestroyEntity(EntityHandle handle);
//component methods
template<class Component, class... Args>
void AddComponent(EntityHandle handle, Component* component, Args*... args)
{
AddComponent(handle, component);
AddComponent(handle, args...);
}
template<class Component>
void AddComponent(EntityHandle handle, Component* component)
{
AddComponentInternal(handle, ECSComponent<Component>::familyID, (BaseECSComponent*)component);
}
我使用的是实体组件系统系统,而 EntityHandle 是对实体的 ID 引用。
CreateEntity 将 id 返回给一个对象。起初我调用 AddComponent(entityHandle, &component) 来添加新组件(它们在我的 ECS 系统中保存为指针)但是当我开始在运行时创建对象以及当我想在循环中创建很多对象时,这变得很烦人。
可能的解决方案?:
使用“new”关键字创建新实体:
EntityHandle entity = CreateEntity(new TransformComponent(position), new RenderComponent(color));
但是,这要求我的所有结构组件都具有设置其所有值的构造函数。
编辑: 我在这里可能完全错了,但我认为我要求的是一种将堆栈对象“转换”为堆对象的方法,这可能是不可能的?