在处理Bevy中的实体时,应该始终使用它们的ID来引用其他实体,不要在系统运行之间存储指向这些实体的指针。
Bevy中的实体ID存储在结构体Entity
中。注意:
实体的轻量级唯一标识符。
此外,如果此网络对于您的游戏是独特的(例如,在整个游戏中最多只有一个实例),则可以将其连通性数据存储在"资源"中。当您创建和处理大量实体和组件时,可以获得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.
}
struct Network { negatives: HashMap<Entity, Vec<Entity>>, positive_conns: HashMap<Entity, Vec<Entity>> }
。因此,如果我有LED的ID,我们可以查找它有哪些连接,然后从查询中查询其他组件。如果我有多个网络,我可以将这些连接存储在单独的组件中(例如struct PositiveConnections(Vec<Entity>)
),并将它们附加到网络的每个部分。 - Angelicos Phosphoros