mirror of
https://github.com/bevyengine/bevy
synced 2024-11-26 22:50:19 +00:00
f574c2c547
Render text in 2D scenes
52 lines
1.7 KiB
Rust
52 lines
1.7 KiB
Rust
use bevy::{
|
|
diagnostic::{Diagnostics, FrameTimeDiagnosticsPlugin},
|
|
prelude::*,
|
|
};
|
|
|
|
/// This example illustrates how to create UI text and update it in a system. It displays the
|
|
/// current FPS in the upper left hand corner. For text within a scene, please see the text2d example.
|
|
fn main() {
|
|
App::build()
|
|
.add_plugins(DefaultPlugins)
|
|
.add_plugin(FrameTimeDiagnosticsPlugin::default())
|
|
.add_startup_system(setup.system())
|
|
.add_system(text_update_system.system())
|
|
.run();
|
|
}
|
|
|
|
// A unit struct to help identify the FPS UI component, since there may be many Text components
|
|
struct FpsText;
|
|
|
|
fn text_update_system(diagnostics: Res<Diagnostics>, mut query: Query<&mut Text, With<FpsText>>) {
|
|
for mut text in query.iter_mut() {
|
|
if let Some(fps) = diagnostics.get(FrameTimeDiagnosticsPlugin::FPS) {
|
|
if let Some(average) = fps.average() {
|
|
text.value = format!("FPS: {:.2}", average);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
fn setup(commands: &mut Commands, asset_server: Res<AssetServer>) {
|
|
commands
|
|
// UI camera
|
|
.spawn(CameraUiBundle::default())
|
|
// texture
|
|
.spawn(TextBundle {
|
|
style: Style {
|
|
align_self: AlignSelf::FlexEnd,
|
|
..Default::default()
|
|
},
|
|
text: Text {
|
|
value: "FPS:".to_string(),
|
|
font: asset_server.load("fonts/FiraSans-Bold.ttf"),
|
|
style: TextStyle {
|
|
font_size: 60.0,
|
|
color: Color::WHITE,
|
|
..Default::default()
|
|
},
|
|
},
|
|
..Default::default()
|
|
})
|
|
.with(FpsText);
|
|
}
|