src/bin/lesson02_bevy_ui.rs

教程导航 · 代码索引

src/bin/lesson02_bevy_ui.rs

教程导航 · 代码索引

原文件:Doc/tutorial/src/bin/lesson02_bevy_ui.rs。

阅读快照 以下内容来自 2026-11-17 导入时的本地源码,后续不会自动同步。编辑、编译和运行请回到原项目;本页 Markdown 不是可直接编译的源文件。

在原项目根目录运行:

cargo run --manifest-path Doc/tutorial/Cargo.toml --bin lesson02_bevy_ui
use bevy::prelude::*;
use bevy_immediate_tutorial::{app, camera, panel};

#[derive(Component)]
struct CounterLabel;

#[derive(Resource, Default)]
struct Counter {
    value: u32,
}

fn main() {
    app("02 - Bevy UI")
        .init_resource::<Counter>()
        .add_systems(Startup, (camera, setup))
        .add_systems(Update, (read_keyboard, update_label).chain())
        .run();
}

fn setup(mut commands: Commands) {
    commands.spawn(panel()).with_children(|parent| {
        parent.spawn((Text::new("Press Space to add one"), TextFont::default()));
        parent.spawn((CounterLabel, Text::new("Count: 0"), TextFont::default()));
    });
}

fn read_keyboard(keys: Res<ButtonInput<KeyCode>>, mut counter: ResMut<Counter>) {
    if keys.just_pressed(KeyCode::Space) {
        counter.value += 1;
    }
}

fn update_label(counter: Res<Counter>, mut labels: Query<&mut Text, With<CounterLabel>>) {
    for mut text in &mut labels {
        let next = format!("Count: {}", counter.value);
        if text.0 != next {
            text.0 = next;
        }
    }
}