Latest commit ffecb05

use bevy::prelude::*;

/// 查询在当前帧的前一阶段中删除了特定组件的实体
/// 说明了怎样才能知道何时删除了组件,并做出相关处理
fn main() {
    // 有关已移除的“组件”的信息会在每帧的末尾被丢弃,因此要在帧结束之前处理相关问题
    //
    // 此外,因为是用“命令”移除“组件”,并且在阶段执行完成后应用“命令”,
    // 所以要在“组件”被移除后的某个阶段内处理相关问题
    //
    // 因此,移除“组件”的系统放在`CoreStage::Update`阶段,移除检测的系统放在`CoreStage::PostUpdate`阶段
    App::new()
        .add_plugins(DefaultPlugins)
        .add_startup_system(初始设置)
        .add_system_to_stage(CoreStage::Update, 移除组件)
        .add_syatem_to_stage(CoreStage::PostUpdate, 移除检测)
        .run();
}

// 这个结构体是示例,先添加给实体,然后移除
#[derive(Component)]
struct MyComponent;

fn 初始设置(
    mut commands: Commands,
    asset_server: Res<AssetServer>,
) {
    let image_handle = asset_server.load("icon.png");
    commands.spwan_bundle(OrthographicCameraBundle::new_2d());
    commands
        .spawn_bundle(SpriteBundle {
            texture: image_handle,
            ..Default::default()
        })
        .insert(MyComponent); // 添加组件
}

fn 移除组件(
    time: Res<Time>,
    mut commands: Commands,
    query: Query<Entity, With<MyComponent>>,
) {
    // 两秒钟后移除组件
    if time.seconds_since_startup() > 2.0 {
        if let Some(entity) = query.iter().next() {
            commands.entity(entity).remove::<MyComponent>();
        }
    }
}

fn 移除检测(
    mut materials: ResMut<Assets<ColorMaterial>>,
    removed: RemovedComponents<MyComponent>,
    query: Query<(Entity, &Handle<ColorMaterial>)>,
) {
    // `RemovedComponents<T>::iter()`返回一个迭代器,
    // 该迭代器的'Entity'在帧的前面某个点删除了'Component``T`(在本例中是'MyComponent`)
    for entity in removed.iter() {
        // 把已经移除了`MyComponent`组件的实体和查询中的实体进行比较,如果匹配,就从材质中删除所有红色
        if let Ok(mut sprite) = query.get_mut(entity) {
            sprite.color.set(0.0);
        }
    }
}