Implement enabled flag for fps overlay (#15246)

# Objective

Fixes #15223 

## Solution

Adds an `enabled` flag to the `FpsOverlayConfig` resource with a system
that detects it's change, and adjusts the visibility of the overlay text
entity.

## Testing

I extended the `fps_overlay` example with the option to toggle the
overlay. Run with:
```
cargo run --features="bevy_dev_tools" --example fps_overlay
```
This commit is contained in:
no-materials 2024-09-17 17:16:28 +02:00 committed by GitHub
parent 3c41586154
commit b884f96598
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 24 additions and 2 deletions

View file

@ -5,12 +5,14 @@ use bevy_asset::Handle;
use bevy_color::Color;
use bevy_diagnostic::{DiagnosticsStore, FrameTimeDiagnosticsPlugin};
use bevy_ecs::{
change_detection::DetectChangesMut,
component::Component,
query::With,
schedule::{common_conditions::resource_changed, IntoSystemConfigs},
system::{Commands, Query, Res, Resource},
};
use bevy_hierarchy::{BuildChildren, ChildBuild};
use bevy_render::view::Visibility;
use bevy_text::{Font, Text, TextSection, TextStyle};
use bevy_ui::{
node_bundles::{NodeBundle, TextBundle},
@ -47,7 +49,7 @@ impl Plugin for FpsOverlayPlugin {
.add_systems(
Update,
(
customize_text.run_if(resource_changed::<FpsOverlayConfig>),
(customize_text, toggle_display).run_if(resource_changed::<FpsOverlayConfig>),
update_text,
),
);
@ -59,6 +61,8 @@ impl Plugin for FpsOverlayPlugin {
pub struct FpsOverlayConfig {
/// Configuration of text in the overlay.
pub text_config: TextStyle,
/// Displays the FPS overlay if true.
pub enabled: bool,
}
impl Default for FpsOverlayConfig {
@ -69,6 +73,7 @@ impl Default for FpsOverlayConfig {
font_size: 32.0,
color: Color::WHITE,
},
enabled: true,
}
}
}
@ -119,3 +124,15 @@ fn customize_text(
}
}
}
fn toggle_display(
overlay_config: Res<FpsOverlayConfig>,
mut query: Query<&mut Visibility, With<FpsText>>,
) {
for mut visibility in &mut query {
visibility.set_if_neq(match overlay_config.enabled {
true => Visibility::Visible,
false => Visibility::Hidden,
});
}
}

View file

@ -19,6 +19,7 @@ fn main() {
// If we want, we can use a custom font
font: default(),
},
enabled: true,
},
},
))
@ -47,7 +48,8 @@ fn setup(mut commands: Commands) {
c.spawn(TextBundle::from_section(
concat!(
"Press 1 to change color of the overlay.\n",
"Press 2 to change size of the overlay."
"Press 2 to change size of the overlay.\n",
"Press 3 to toggle the overlay."
),
TextStyle::default(),
));
@ -62,4 +64,7 @@ fn customize_config(input: Res<ButtonInput<KeyCode>>, mut overlay: ResMut<FpsOve
if input.just_pressed(KeyCode::Digit2) {
overlay.text_config.font_size -= 2.0;
}
if input.just_pressed(KeyCode::Digit3) {
overlay.enabled = !overlay.enabled;
}
}