gpt4 book ai didi

使用rust (Bevy) : ECS Network data structure

转载 作者:行者123 更新时间:2023-12-05 04:30:11 26 4
gpt4 key购买 nike

我不太确定我是否完全理解实体组件系统方法,这可能是出现此问题的原因之一。仍在与 OOP 思维方式作斗争!

我正在尝试创建一个类似于网络的数据结构,例如,类似于电路的东西:

Circuit.

因此,例如,实体 4 连接到 1、1 连接到 2,依此类推。到目前为止,我已经了解了如何创建组件,但我不明白应该如何存储连接信息。我相信实体应该指向另一个实体?!?我还想象过拥有一个具有连接信息的组件会更好,但在那种情况下,它应该再次存储什么?理想情况下是实体本身,对吧?怎么做?

最佳答案

您应该始终使用其他实体的 ID 来引用其他实体,并且不要在系统运行之间存储指向它们的指针。

Bevy 中的实体 ID 存储在结构 Entity 中注意:

Lightweight unique ID of an entity.

此外,如果此网络对于您的游戏来说是独一无二的(例如,整个游戏中最多有一个实例),那么它的连接数据可以存储在 "resource" 中。 .当您的实体和组件被大量创建和处理时,您将从 ECS 的实体组件部分获得最大 yield 。

关于您的特定用例,我无法多说什么,因为我不知道会有多少个网络,您计划如何使用它们并与它们交互。 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.
}

关于使用rust (Bevy) : ECS Network data structure,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72111026/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com