我不太确定我是否完全理解实体组件系统方法,这可能是这个问题出现的原因之一。还在和OOP的思维方式做斗争!
我试图创建一个类似于网络的数据结构,例如,某种类似于电路的东西:
因此,例如,实体4连接到1,1到2,等等。到目前为止,我已经了解了如何创建组件,但无法理解如何存储连接信息。我认为这个实体应该指向另一个实体?我还设想过,如果有一个具有连接性信息的组件,这将是更好的实践,但在这种情况下,它应该存储什么呢?理想情况下是实体本身,对吗?该怎么做呢?
发布于 2022-07-16 18:15:32
您应该始终使用它们的Id引用其他实体,并且不要在系统运行之间存储指向它们的指针。
存储在struct Entity中的实体id
实体的轻量级唯一ID。
另外,如果这个网络对于您的游戏是独一无二的(例如,整个游戏中有最大一个实例),那么它的连接数据可以存储在“资源”中。当大量创建和处理实体和组件时,您将从ECS的实体组件部分获得最大的好处。
我不能说更多关于你的特定用例,因为我不知道会有多少网络,你计划如何使用它们并与它们互动。ECS是DDD模式(数据驱动的开发),因此体系结构取决于存在多少数据、该数据具有哪些属性以及如何使用它。
多网络实例
如果您有多个网络,您可以以这样的方式存储它们:
#[derive(Component)]
struct NetworkTag; // Any entity with this tag is network.
// Spawn network into world like this
let network_id: Entity = world.spawn()
.insert(NetworkTag)
.id();而且你可以以这样的方式存储部分的电网:
#[derive(Component)]
struct PlusConnections(Vec<Entity>);
#[derive(Component)]
struct NetworkId(Entity);
// Spawn part into world like this
let part_id = world.spawn()
.insert(NetworkId(network_id))
.insert(PlusConnections(other_part_ids));在完成这样的产卵部分之后,您将只知道正面的连接,但是您可以在单独的系统中填充负面的部分,例如:
#[derive(Component)]
struct NegConnections(Vec<Entity>);
fn fill_negatives_system(
query_el_parts: Query<(Entity, &PlusConnections)>,
query_el_parts_wo_neg: Query<Entity, Without<NegConnections>>,
mut commands: Commands
){
let mut positive_to_negative: HashMap<Entity, Vec<Entity>> = HashMap::new();
for (neg, pc) in query_el_parts.iter(){
for &positivein pc.0.iter(){
positive_to_negative.entry(positive).or_default().push(neg);
}
}
for (pos, negatives) in positive_to_negative{
commands.entity(pos).insert(NegConnections(negatives));
}
// At the next tick, all nodes in electric grid would know what is their negative and positive connections and in which networks they are stored.
}https://stackoverflow.com/questions/72111026
复制相似问题