sub_states/
sub_states.rs

1//! This example illustrates the use of [`SubStates`] for more complex state handling patterns.
2//!
3//! [`SubStates`] are [`States`] that only exist while the App is in another [`State`]. They can
4//! be used to create more complex patterns while relying on simple enums, or to de-couple certain
5//! elements of complex state objects.
6//!
7//! In this case, we're transitioning from a `Menu` state to an `InGame` state, at which point we create
8//! a substate called `IsPaused` to track whether the game is paused or not.
9
10use bevy::{dev_tools::states::*, prelude::*};
11
12use ui::*;
13
14#[derive(Debug, Clone, Copy, Default, Eq, PartialEq, Hash, States)]
15enum AppState {
16    #[default]
17    Menu,
18    InGame,
19}
20
21// In this case, instead of deriving `States`, we derive `SubStates`
22#[derive(Debug, Clone, Copy, Default, Eq, PartialEq, Hash, SubStates)]
23// And we need to add an attribute to let us know what the source state is
24// and what value it needs to have. This will ensure that unless we're
25// in [`AppState::InGame`], the [`IsPaused`] state resource
26// will not exist.
27#[source(AppState = AppState::InGame)]
28#[states(scoped_entities)]
29enum IsPaused {
30    #[default]
31    Running,
32    Paused,
33}
34
35fn main() {
36    App::new()
37        .add_plugins(DefaultPlugins)
38        .init_state::<AppState>()
39        .add_sub_state::<IsPaused>() // We set the substate up here.
40        // Most of these remain the same
41        .add_systems(Startup, setup)
42        .add_systems(OnEnter(AppState::Menu), setup_menu)
43        .add_systems(Update, menu.run_if(in_state(AppState::Menu)))
44        .add_systems(OnExit(AppState::Menu), cleanup_menu)
45        .add_systems(OnEnter(AppState::InGame), setup_game)
46        .add_systems(OnEnter(IsPaused::Paused), setup_paused_screen)
47        .add_systems(
48            Update,
49            (
50                // Instead of relying on [`AppState::InGame`] here, we're relying on
51                // [`IsPaused::Running`], since we don't want movement or color changes
52                // if we're paused
53                (movement, change_color).run_if(in_state(IsPaused::Running)),
54                // The pause toggle, on the other hand, needs to work whether we're
55                // paused or not, so it uses [`AppState::InGame`] instead.
56                toggle_pause.run_if(in_state(AppState::InGame)),
57            ),
58        )
59        .add_systems(Update, log_transitions::<AppState>)
60        .run();
61}
62
63fn menu(
64    mut next_state: ResMut<NextState<AppState>>,
65    mut interaction_query: Query<
66        (&Interaction, &mut BackgroundColor),
67        (Changed<Interaction>, With<Button>),
68    >,
69) {
70    for (interaction, mut color) in &mut interaction_query {
71        match *interaction {
72            Interaction::Pressed => {
73                *color = PRESSED_BUTTON.into();
74                next_state.set(AppState::InGame);
75            }
76            Interaction::Hovered => {
77                *color = HOVERED_BUTTON.into();
78            }
79            Interaction::None => {
80                *color = NORMAL_BUTTON.into();
81            }
82        }
83    }
84}
85
86fn cleanup_menu(mut commands: Commands, menu_data: Res<MenuData>) {
87    commands.entity(menu_data.button_entity).despawn();
88}
89
90const SPEED: f32 = 100.0;
91fn movement(
92    time: Res<Time>,
93    input: Res<ButtonInput<KeyCode>>,
94    mut query: Query<&mut Transform, With<Sprite>>,
95) {
96    for mut transform in &mut query {
97        let mut direction = Vec3::ZERO;
98        if input.pressed(KeyCode::ArrowLeft) {
99            direction.x -= 1.0;
100        }
101        if input.pressed(KeyCode::ArrowRight) {
102            direction.x += 1.0;
103        }
104        if input.pressed(KeyCode::ArrowUp) {
105            direction.y += 1.0;
106        }
107        if input.pressed(KeyCode::ArrowDown) {
108            direction.y -= 1.0;
109        }
110
111        if direction != Vec3::ZERO {
112            transform.translation += direction.normalize() * SPEED * time.delta_secs();
113        }
114    }
115}
116
117fn change_color(time: Res<Time>, mut query: Query<&mut Sprite>) {
118    for mut sprite in &mut query {
119        let new_color = LinearRgba {
120            blue: ops::sin(time.elapsed_secs() * 0.5) + 2.0,
121            ..LinearRgba::from(sprite.color)
122        };
123
124        sprite.color = new_color.into();
125    }
126}
127
128fn toggle_pause(
129    input: Res<ButtonInput<KeyCode>>,
130    current_state: Res<State<IsPaused>>,
131    mut next_state: ResMut<NextState<IsPaused>>,
132) {
133    if input.just_pressed(KeyCode::Space) {
134        next_state.set(match current_state.get() {
135            IsPaused::Running => IsPaused::Paused,
136            IsPaused::Paused => IsPaused::Running,
137        });
138    }
139}
140
141mod ui {
142    use crate::*;
143
144    #[derive(Resource)]
145    pub struct MenuData {
146        pub button_entity: Entity,
147    }
148
149    pub const NORMAL_BUTTON: Color = Color::srgb(0.15, 0.15, 0.15);
150    pub const HOVERED_BUTTON: Color = Color::srgb(0.25, 0.25, 0.25);
151    pub const PRESSED_BUTTON: Color = Color::srgb(0.35, 0.75, 0.35);
152
153    pub fn setup(mut commands: Commands) {
154        commands.spawn(Camera2d);
155    }
156
157    pub fn setup_menu(mut commands: Commands) {
158        let button_entity = commands
159            .spawn((
160                Node {
161                    // center button
162                    width: percent(100),
163                    height: percent(100),
164                    justify_content: JustifyContent::Center,
165                    align_items: AlignItems::Center,
166                    ..default()
167                },
168                children![(
169                    Button,
170                    Node {
171                        width: px(150),
172                        height: px(65),
173                        // horizontally center child text
174                        justify_content: JustifyContent::Center,
175                        // vertically center child text
176                        align_items: AlignItems::Center,
177                        ..default()
178                    },
179                    BackgroundColor(NORMAL_BUTTON),
180                    children![(
181                        Text::new("Play"),
182                        TextFont {
183                            font_size: 33.0,
184                            ..default()
185                        },
186                        TextColor(Color::srgb(0.9, 0.9, 0.9)),
187                    )]
188                )],
189            ))
190            .id();
191        commands.insert_resource(MenuData { button_entity });
192    }
193
194    pub fn setup_game(mut commands: Commands, asset_server: Res<AssetServer>) {
195        commands.spawn(Sprite::from_image(asset_server.load("branding/icon.png")));
196    }
197
198    pub fn setup_paused_screen(mut commands: Commands) {
199        commands.spawn((
200            DespawnOnExit(IsPaused::Paused),
201            Node {
202                // center button
203                width: percent(100),
204                height: percent(100),
205                justify_content: JustifyContent::Center,
206                align_items: AlignItems::Center,
207                flex_direction: FlexDirection::Column,
208                row_gap: px(10),
209                ..default()
210            },
211            children![(
212                Node {
213                    width: px(400),
214                    height: px(400),
215                    // horizontally center child text
216                    justify_content: JustifyContent::Center,
217                    // vertically center child text
218                    align_items: AlignItems::Center,
219                    ..default()
220                },
221                BackgroundColor(NORMAL_BUTTON),
222                children![(
223                    Text::new("Paused"),
224                    TextFont {
225                        font_size: 33.0,
226                        ..default()
227                    },
228                    TextColor(Color::srgb(0.9, 0.9, 0.9)),
229                )]
230            )],
231        ));
232    }
233}