3

我正在关注使用Specs ECS 的 rust 教程,我正在尝试使用legion ECS来实现它。我喜欢军团,一切都很顺利,直到我遇到问题。

我不确定如何提出我的问题。我想要做的是创建一个系统,该系统在每个具有例如 ComponentA 和 ComponentB 的实体上进行迭代,但它也会检查实体是否具有 ComponentC 并在这种情况下做一些特殊的事情。

我可以使用规格(示例代码)这样​​做:

// Uses Specs
pub struct SystemA {}

impl<'a> System<'a> for SystemA {
    type SystemData = ( Entities<'a>,
                        WriteStorage<'a, ComponentA>, 
                        ReadStorage<'a, ComponentB>,
                        ReadStorage<'a, ComponentC>);

    fn run(&mut self, data : Self::SystemData) {
        let (entities, mut compA, compB, compC) = data;

        // Finding all entities with ComponentA and ComponentB
        for (ent, compA, compB) in (&entities, &mut compA, &compB).join() {
            // Do stuff with compA and compB

            // Check if Entity also has ComponentC
            let c : Option<&ComponentC> = compC.get(ent);

            if let Some(c) = c {
                // Do something special with entity if it also has ComponentC
            }
        }
    }
}

我很难将其转换为使用军团(当前使用最新的 0.4.0 版本)。我不知道如何获取当前实体拥有的其他组件。这是我的代码:

#[system(for_each)]
pub fn systemA(entity: &Entity, compA: &mut compA, compB: &mut ComponentB) {
    // Do stuff with compA and compB

    // How do I check if entity has compC here?

}

上述系统中的实体仅包含其 ID。如何在没有 World 的情况下访问该实体的组件列表?或者有没有办法在军团系统中访问世界?或者任何其他方式来实现与 Specs 版本相同的效果?

谢谢!

4

1 回答 1

2

您可以将Option <...> 用于可选组件。

#[system(for_each)]
pub fn systemA(entity: &Entity, compA: &mut compA, compB: &mut ComponentB, compC: Option<&ComponentC>) {
    ...
    if let Some(compC) = compC {
        // this entity has compC
        ...
于 2021-03-10T14:48:40.697 回答