不常见的system

ECS是一个完整的体系,不管是component还是system的参数解析信息都有cache, 这样能显著提高性能,另外各调度的延后执行让并行概率提高,这都得益于ECS的设计.

那么有没有这么一个system,不仅仅使用了system param,还要使用其他非systemparam的参数呢?

bevy有扩展:In,表明system的第一个参数In是调用方传入的.

#[derive(Debug)]
pub struct SpawnPlayer {
    /// See [`MovementController::max_speed`].
    pub max_speed: f32,
}

impl Command for SpawnPlayer {
    fn apply(self, world: &mut World) {
        let _ = world.run_system_cached_with(spawn_player, self);
    }
}

fn spawn_player(
    In(config): In<SpawnPlayer>,
    mut commands: Commands,
    player_assets: Res<PlayerAssets>,
    mut texture_atlas_layouts: ResMut<Assets<TextureAtlasLayout>>,
) {
    let layout = TextureAtlasLayout::from_grid(UVec2::splat(32), 6, 2, Some(UVec2::splat(1)), None);
    let texture_atlas_layout = texture_atlas_layouts.add(layout);
    let player_animation = PlayerAnimation::new();

    commands.spawn((
        Name::new("Player"),
        Player,
        Sprite {
            image: player_assets.ducky.clone(),
            texture_atlas: Some(TextureAtlas {
                layout: texture_atlas_layout.clone(),
                index: player_animation.get_atlas_index(),
            }),
            ..default()
        },
        Transform::from_scale(Vec2::splat(8.0).extend(1.0)),
        MovementController {
            max_speed: config.max_speed,
            ..default()
        },
        ScreenWrap,
        player_animation,
        StateScoped(Screen::Gameplay),
    ));
}

spawn_player不是标准的system,但也能像system一样执行,这里启用了system缓存,减少了参数解析校验的事. 标准的ECS已经默认包含了参数解析等缓存手段.

这里面只是一种调用system的方式,仅用在某些特殊场景.

就算使用In(T)参数,也只能放在system的第一个参数,且最多只能有一个,这点和Trigger是一样的.