From edba5d013d7613478d48e4cbea12bda2ebfe4464 Mon Sep 17 00:00:00 2001 From: Felix Ableitner Date: Sun, 3 Jan 2021 17:43:39 +0100 Subject: [PATCH] Display FPS in hud (copied from example) --- src/hud.rs | 58 +++++++++++++++++++++++++++++++++++++++++++++++++++++ src/lib.rs | 1 + src/main.rs | 3 ++- 3 files changed, 61 insertions(+), 1 deletion(-) create mode 100644 src/hud.rs diff --git a/src/hud.rs b/src/hud.rs new file mode 100644 index 0000000..1c3d8fd --- /dev/null +++ b/src/hud.rs @@ -0,0 +1,58 @@ +use bevy::{ + diagnostic::{Diagnostics, FrameTimeDiagnosticsPlugin}, + prelude::*, +}; + +pub struct HudPlugin; + +impl Plugin for HudPlugin { + fn build(&self, app: &mut AppBuilder) { + app + .add_plugin(FrameTimeDiagnosticsPlugin::default()) + .add_startup_system(setup.system()) + .add_system(fps_update_system.system()); + } +} + +// A unit struct to help identify the FPS UI component, since there may be many Text components +struct FpsText; + +fn fps_update_system(diagnostics: Res, mut query: Query<&mut Text, With>) { + for mut text in query.iter_mut() { + if let Some(fps) = diagnostics.get(FrameTimeDiagnosticsPlugin::FPS) { + if let Some(average) = fps.value() { + text.value = format!("{:.0} fps", average); + } + } + } +} + +fn setup(commands: &mut Commands, asset_server: Res) { + commands + // UI camera + .spawn(CameraUiBundle::default()) + // texture + .spawn(TextBundle { + style: Style { + align_self: AlignSelf::FlexEnd, + position_type: PositionType::Absolute, + position: Rect { + top: Val::Px(5.0), + right: Val::Px(5.0), + ..Default::default() + }, + ..Default::default() + }, + text: Text { + value: "".to_string(), + font: asset_server.load("fonts/FiraMono-Medium.ttf"), + style: TextStyle { + font_size: 16.0, + color: Color::WHITE, + ..Default::default() + }, + }, + ..Default::default() + }) + .with(FpsText); +} diff --git a/src/lib.rs b/src/lib.rs index 50f34a8..9527b01 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,2 +1,3 @@ +pub mod hud; pub mod player; pub mod world; diff --git a/src/main.rs b/src/main.rs index f7a972d..3130509 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,6 +1,6 @@ use bevy::{input::system::exit_on_esc_system, prelude::*}; use bevy_rapier3d::physics::RapierPhysicsPlugin; -use rake::{player::PlayerPlugin, world::WorldPlugin}; +use rake::{hud::HudPlugin, player::PlayerPlugin, world::WorldPlugin}; fn main() { App::build() @@ -16,6 +16,7 @@ fn main() { // note: debug renderer doesnt work for cylinder //.add_plugin(RapierRenderPlugin) .add_plugin(PlayerPlugin) + .add_plugin(HudPlugin) .add_plugin(WorldPlugin) .add_system(exit_on_esc_system.system()) .run();