Skip to main content

traaains/game/
pausing.rs

1use bevy::{
2    app::{Plugin, Startup, Update},
3    ecs::{
4        component::Component,
5        query::With,
6        resource::Resource,
7        schedule::IntoScheduleConfigs,
8        system::{Commands, ResMut, Single},
9    },
10    input::{common_conditions::input_just_pressed, keyboard::KeyCode},
11    text::TextSpan,
12    ui::{Node, PositionType, px, widget::Text},
13};
14
15#[derive(PartialEq, Eq, Resource)]
16pub struct IsPaused(pub bool);
17
18#[derive(Component)]
19struct PausedText;
20
21fn setup_paused(mut cmd: Commands) {
22    cmd.spawn((
23        Text::new(""),
24        Node {
25            position_type: PositionType::Absolute,
26            top: px(5),
27            right: px(5),
28            ..Default::default()
29        },
30    ))
31    .with_child((TextSpan::new("Playing"), PausedText));
32}
33
34fn update_paused(
35    paused_text: Single<&mut TextSpan, With<PausedText>>,
36    mut is_paused: ResMut<IsPaused>,
37) {
38    is_paused.0 = !is_paused.0;
39    let mut paused_text = paused_text.into_inner();
40    paused_text.0 = match is_paused.0 {
41        true => "Paused".to_string(),
42        false => "Playing".to_string(),
43    }
44}
45
46pub struct PausingPlugin;
47
48impl Plugin for PausingPlugin {
49    fn build(&self, app: &mut bevy::app::App) {
50        app.insert_resource(IsPaused(false))
51            .add_systems(Startup, setup_paused)
52            .add_systems(
53                Update,
54                update_paused.run_if(input_just_pressed(KeyCode::Space)),
55            );
56    }
57}