佐藤のメモ帳

Rust, Python, Java, AWS, etc...

Rust Bevy Commandについて

はじめに

本記事はBevy非公式(と思えないほど素晴らしい)サイトのメモである。

bevy-cheatbook.github.io

メモ

BevyにおいてCommandとはEntityのスポーン・デスポーンやEntityへのComponent追加・削除、Resourceを管理する機能である。

Commandの操作は即座に反映されない、Commandを実行するとキューが生成され、Bevyがよしなにいいタイミングで処理をする。

以下使用例

fn spawn_player(
    mut commands: Commands,
) {
    // Resourceの管理
    commands.insert_resource(GoalsReached { main_goal: false, bonus: false });
    commands.remove_resource::<MyResource>();

    // `spawn`で新しいEntityを作成
    let entity_id = commands.spawn()
        // Componentを追加
        .insert(ComponentA)
        // Bundleを追加
        .insert_bundle(MyBundle::default())
        // EntityのIDを取得
        .id();

    // BundleでEntityを作成するショートハンド
    commands.spawn_bundle(PlayerBundle {
        name: PlayerName("Henry".into()),
        xp: PlayerXp(1000),
        health: Health {
            hp: 100.0, extra: 20.0
        },
        _p: Player,
        sprite: Default::default(),
    });

    // Entityをスポーン
    // 注意: 任意のComponentのタプルはBundleとして判断される
    let other = commands.spawn_bundle((
        ComponentA::default(),
        ComponentB::default(),
        ComponentC::default(),
    )).id();

    // すでに作成しているEntityにComponentを追加 or EntityからComponentを削除
    commands.entity(entity_id)
        .insert(ComponentB)
        .remove::<ComponentA>()
        .remove_bundle::<MyBundle>();

    // Entityをデスポーン
    commands.entity(other).despawn();
}

fn make_all_players_hostile(
    mut commands: Commands,
    query: Query<Entity, With<Player>>,
) {
    for entity in query.iter() {
        // 指定したEntityに`Enemy`Componentを追加
        commands.entity(entity).insert(Enemy);
    }
}