add HUD with FPS display

This commit is contained in:
yuni 2024-03-17 15:23:22 +01:00
parent 3e305baf87
commit a72b76a234
2 changed files with 73 additions and 1 deletions

68
src/hud.rs Normal file
View file

@ -0,0 +1,68 @@
use bevy::prelude::*;
use bevy::diagnostic::{DiagnosticsStore, FrameTimeDiagnosticsPlugin};
pub struct OutFlyHudPlugin;
impl Plugin for OutFlyHudPlugin {
fn build(&self, app: &mut App) {
app.add_systems(Startup, setup);
app.add_systems(Update, update);
app.insert_resource(FPSUpdateTimer(Timer::from_seconds(0.25, TimerMode::Repeating)));
}
}
#[derive(Component)]
struct FpsText;
#[derive(Resource)]
struct FPSUpdateTimer(Timer);
fn setup(
mut commands: Commands,
) {
commands.spawn((
TextBundle::from_sections([
TextSection::new(
"FPS: ",
TextStyle {
//font: asset_server.load("fonts/FiraSans-Bold.ttf"),
font_size: 60.0,
..default()
},
),
TextSection::from_style(if cfg!(feature = "default_font") {
TextStyle {
font_size: 60.0,
color: Color::GOLD,
..default()
}
} else {
// "default_font" feature is unavailable, load a font to use instead.
TextStyle {
//font: asset_server.load("fonts/FiraMono-Medium.ttf"),
font_size: 60.0,
color: Color::GOLD,
..default()
}
}),
]),
FpsText,
));
}
fn update(
diagnostics: Res<DiagnosticsStore>,
time:Res<Time>,
mut timer: ResMut<FPSUpdateTimer>,
mut query: Query<&mut Text, With<FpsText>>,
) {
if timer.0.tick(time.delta()).just_finished() {
for mut text in &mut query {
if let Some(fps) = diagnostics.get(&FrameTimeDiagnosticsPlugin::FPS) {
if let Some(value) = fps.smoothed() {
// Update the value of the second section
text.sections[1].value = format!("{value:.0}");
}
}
}
}
}

View file

@ -3,6 +3,7 @@ mod player;
mod camera; mod camera;
mod world; mod world;
mod settings; mod settings;
mod hud;
use bevy::window::{Window, WindowMode, PrimaryWindow, CursorGrabMode }; use bevy::window::{Window, WindowMode, PrimaryWindow, CursorGrabMode };
use bevy::diagnostic::{FrameTimeDiagnosticsPlugin, LogDiagnosticsPlugin}; use bevy::diagnostic::{FrameTimeDiagnosticsPlugin, LogDiagnosticsPlugin};
@ -24,7 +25,10 @@ fn main() {
world::asset_loaded.after(world::load_cubemap_asset), world::asset_loaded.after(world::load_cubemap_asset),
)) ))
.add_plugins(DefaultPlugins.set(ImagePlugin::default_nearest())) .add_plugins(DefaultPlugins.set(ImagePlugin::default_nearest()))
.add_plugins(camera::CameraControllerPlugin) .add_plugins((
camera::CameraControllerPlugin,
hud::OutFlyHudPlugin,
))
.add_plugins(( .add_plugins((
FrameTimeDiagnosticsPlugin, FrameTimeDiagnosticsPlugin,
LogDiagnosticsPlugin::default(), LogDiagnosticsPlugin::default(),