Latest commit c19aa59

创建并更新文本。

use bevy::diagnostic::{Diagnostics, FrameTimeDiagnosticsPlugin};
use bevy::prelude::*;

fn main() {
    let mut app = App::new();

    app.add_plugins(DefaultPlugins);
    app.add_plugin(FrameTimeDiagnosticsPlugin);

    app.add_startup_system(初始设置);
    app.add_system(修改文本颜色);
    app.add_system(修改文本内容);

    app.run();
}

// 标记需要更改颜色的文本
#[derive(Component)]
struct ColorText;

// 标记显示 fps 的文本
#[derive(Component)]
struct FpsText;

fn 初始设置(mut commands: Commands, asset_server: Res<AssetServer>) {
    // 摄像机
    commands.spawn(Camera2dBundle::default());
    // 一节文本
    commands.spawn((
        TextBundle::from_section(
            "你好\nbevy!",
            TextStyle {
                font: asset_server.load("fonts/LXGWWenKai.ttf"),
                font_size: 100.0,
                color: Color::WHITE,
            },
        )
        // 设置文本对齐
        .with_text_alignment(TextAlignment::TOP_CENTER)
        // 设置 TextBundle 的样式
        .with_style(Style {
            position_type: PositionType::Absolute,
            position: UiRect {
                bottom: Val::Px(5.0),
                right: Val::Px(15.0),
                ..default()
            },
            ..default()
        }),
        ColorText,
    ));
    // 几节文本
    commands.spawn((
        TextBundle::from_sections([
            TextSection::new(
                "FPS: ",
                TextStyle {
                    font: asset_server.load("fonts/LXGWWenKai.ttf"),
                    font_size: 60.0,
                    color: Color::WHITE,
                },
            ),
            TextSection::from_style(TextStyle {
                font: asset_server.load("fonts/LXGWWenKai.ttf"),
                font_size: 60.0,
                color: Color::GOLD,
            }),
        ]),
        FpsText,
    ));
}

fn 修改文本颜色(time: Res<Time>, mut query: Query<&mut Text, With<ColorText>>) {
    for mut text in &mut query {
        let seconds = time.elapsed_seconds();
        // 前面用了 TextBundle::from_section(),因此只有“一节”文本
        text.sections[0].style.color = Color::Rgba {
            red: (1.25 * seconds).sin() / 2.0 + 0.5,
            green: (0.75 * seconds).sin() / 2.0 + 0.5,
            blue: (0.50 * seconds).sin() / 2.0 + 0.5,
            alpha: 1.0,
        };
    }
}

fn 修改文本内容(diagnostics: Res<Diagnostics>, mut query: Query<&mut Text, With<FpsText>>) {
    for mut text in &mut query {
        if let Some(fps) = diagnostics.get(FrameTimeDiagnosticsPlugin::FPS) {
            if let Some(value) = fps.smoothed() {
                // 前面用了 TextBundle::from_sections(),因此有“几节”文本
                // 这里修改的是 “FPS: ” 后面的数字
                text.sections[1].value = format!("{value:.2}");
            }
        }
    }
}