Skip to main content

custom_transitions/
custom_transitions.rs

1//! This example illustrates how to register custom state transition behavior.
2//!
3//! In this case we are trying to add `OnReenter` and `OnReexit`
4//! which will work much like `OnEnter` and `OnExit`,
5//! but additionally trigger if the state changed into itself.
6//!
7//! While identity transitions exist internally in [`StateTransitionEvent`]s,
8//! the default schedules intentionally ignore them, as this behavior is not commonly needed or expected.
9//!
10//! While this example displays identity transitions for a single state,
11//! identity transitions are propagated through the entire state graph,
12//! meaning any change to parent state will be propagated to [`ComputedStates`] and [`SubStates`].
13
14use std::marker::PhantomData;
15
16use bevy::{
17    dev_tools::states::*,
18    ecs::schedule::ScheduleLabel,
19    picking::hover::Hovered,
20    prelude::*,
21    ui::Pressed,
22    ui_widgets::{Activate, ActivateOnPress, Button},
23};
24
25use custom_transitions::*;
26
27#[derive(Debug, Clone, Copy, Default, Eq, PartialEq, Hash, States)]
28enum AppState {
29    #[default]
30    Menu,
31    InGame,
32}
33
34fn main() {
35    App::new()
36        // We insert the custom transitions plugin for `AppState`.
37        .add_plugins((
38            DefaultPlugins,
39            IdentityTransitionsPlugin::<AppState>::default(),
40        ))
41        .init_state::<AppState>()
42        .add_systems(Startup, setup)
43        .add_systems(OnEnter(AppState::Menu), setup_menu)
44        .add_observer(on_activate_start_game.run_if(in_state(AppState::Menu)))
45        .add_systems(Update, hover_style)
46        .add_systems(OnExit(AppState::Menu), cleanup_menu)
47        // We will restart the game progress every time we re-enter xinto it.
48        .add_observer(trigger_game_restart.run_if(in_state(AppState::InGame)))
49        .add_systems(OnReenter(AppState::InGame), setup_game)
50        .add_systems(OnReexit(AppState::InGame), teardown_game)
51        // Doing it this way allows us to restart the game without any additional in-between states.
52        .add_systems(
53            Update,
54            (movement, change_color).run_if(in_state(AppState::InGame)),
55        )
56        .add_systems(Update, log_transitions::<AppState>)
57        .run();
58}
59
60/// This module provides the custom `OnReenter` and `OnReexit` transitions for easy installation.
61mod custom_transitions {
62    use crate::*;
63
64    /// The plugin registers the transitions for one specific state.
65    /// If you use this for multiple states consider:
66    /// - installing the plugin multiple times,
67    /// - create an [`App`] extension method that inserts
68    ///   those transitions during state installation.
69    #[derive(Default)]
70    pub struct IdentityTransitionsPlugin<S: States>(PhantomData<S>);
71
72    impl<S: States> Plugin for IdentityTransitionsPlugin<S> {
73        fn build(&self, app: &mut App) {
74            app.add_systems(
75                StateTransition,
76                // The internals can generate at most one transition event of specific type per frame.
77                // We take the latest one and clear the queue.
78                last_transition::<S>
79                    // We insert the optional event into our schedule runner.
80                    .pipe(run_reenter::<S>)
81                    // State transitions are handled in three ordered steps, exposed as system sets.
82                    // We can add our systems to them, which will run the corresponding schedules when they're evaluated.
83                    // These are:
84                    // - [`ExitSchedules`] - Ran from leaf-states to root-states,
85                    // - [`TransitionSchedules`] - Ran in arbitrary order,
86                    // - [`EnterSchedules`] - Ran from root-states to leaf-states.
87                    .in_set(EnterSchedules::<S>::default()),
88            )
89            .add_systems(
90                StateTransition,
91                last_transition::<S>
92                    .pipe(run_reexit::<S>)
93                    .in_set(ExitSchedules::<S>::default()),
94            );
95        }
96    }
97
98    /// Custom schedule that will behave like [`OnEnter`], but run on identity transitions.
99    #[derive(ScheduleLabel, Clone, Debug, PartialEq, Eq, Hash)]
100    pub struct OnReenter<S: States>(pub S);
101
102    /// Schedule runner which checks conditions and if they're right
103    /// runs out custom schedule.
104    fn run_reenter<S: States>(transition: In<Option<StateTransitionEvent<S>>>, world: &mut World) {
105        // We return early if no transition event happened.
106        let Some(transition) = transition.0 else {
107            return;
108        };
109
110        // If we wanted to ignore identity transitions,
111        // we'd compare `exited` and `entered` here,
112        // and return if they were the same.
113
114        // We check if we actually entered a state.
115        // A [`None`] would indicate that the state was removed from the world.
116        // This only happens in the case of [`SubStates`] and [`ComputedStates`].
117        let Some(entered) = transition.entered else {
118            return;
119        };
120
121        // If all conditions are valid, we run our custom schedule.
122        let _ = world.try_run_schedule(OnReenter(entered));
123
124        // If you want to overwrite the default `OnEnter` behavior to act like re-enter,
125        // you can do so by running the `OnEnter` schedule here. Note that you don't want
126        // to run `OnEnter` when the default behavior does so.
127        // ```
128        // if transition.entered != transition.exited {
129        //     return;
130        // }
131        // let _ = world.try_run_schedule(OnReenter(entered));
132        // ```
133    }
134
135    /// Custom schedule that will behave like [`OnExit`], but run on identity transitions.
136    #[derive(ScheduleLabel, Clone, Debug, PartialEq, Eq, Hash)]
137    pub struct OnReexit<S: States>(pub S);
138
139    fn run_reexit<S: States>(transition: In<Option<StateTransitionEvent<S>>>, world: &mut World) {
140        let Some(transition) = transition.0 else {
141            return;
142        };
143        let Some(exited) = transition.exited else {
144            return;
145        };
146
147        let _ = world.try_run_schedule(OnReexit(exited));
148    }
149}
150
151fn on_activate_start_game(_: On<Activate>, mut next_state: ResMut<NextState<AppState>>) {
152    next_state.set(AppState::InGame);
153}
154
155fn hover_style(
156    mut button_query: Query<(&Hovered, &mut BackgroundColor), (Changed<Hovered>, With<Button>)>,
157) {
158    for (hovered, mut color) in &mut button_query {
159        if hovered.get() {
160            *color = HOVERED_BUTTON.into();
161        } else {
162            *color = NORMAL_BUTTON.into();
163        }
164    }
165}
166
167fn cleanup_menu(mut commands: Commands, menu_data: Res<MenuData>) {
168    commands.entity(menu_data.button_entity).despawn();
169}
170
171const SPEED: f32 = 100.0;
172fn movement(
173    time: Res<Time>,
174    input: Res<ButtonInput<KeyCode>>,
175    mut query: Query<&mut Transform, With<Sprite>>,
176) {
177    for mut transform in &mut query {
178        let mut direction = Vec3::ZERO;
179        if input.pressed(KeyCode::ArrowLeft) {
180            direction.x -= 1.0;
181        }
182        if input.pressed(KeyCode::ArrowRight) {
183            direction.x += 1.0;
184        }
185        if input.pressed(KeyCode::ArrowUp) {
186            direction.y += 1.0;
187        }
188        if input.pressed(KeyCode::ArrowDown) {
189            direction.y -= 1.0;
190        }
191
192        if direction != Vec3::ZERO {
193            transform.translation += direction.normalize() * SPEED * time.delta_secs();
194        }
195    }
196}
197
198fn change_color(time: Res<Time>, mut query: Query<&mut Sprite>) {
199    for mut sprite in &mut query {
200        let new_color = LinearRgba {
201            blue: ops::sin(time.elapsed_secs() * 0.5) + 2.0,
202            ..LinearRgba::from(sprite.color)
203        };
204
205        sprite.color = new_color.into();
206    }
207}
208
209// We can restart the game by pressing the restart button.
210// This will trigger an [`AppState::InGame`] -> [`AppState::InGame`]
211// transition, which will run our custom schedules.
212fn trigger_game_restart(_: On<Activate>, mut next_state: ResMut<NextState<AppState>>) {
213    // Although we are already in this state setting it again will generate an identity transition.
214    // While default schedules ignore those kinds of transitions, our custom schedules will react to them.
215    next_state.set(AppState::InGame);
216}
217
218fn setup(mut commands: Commands) {
219    commands.spawn(Camera2d);
220}
221
222fn setup_game(mut commands: Commands, asset_server: Res<AssetServer>) {
223    commands.spawn(Sprite::from_image(asset_server.load("branding/icon.png")));
224    commands.spawn_scene(bsn! {
225        Node {
226            width: percent(100),
227            height: percent(100),
228        }
229        Children [
230            Node {
231                position_type: PositionType::Absolute,
232                left: px(10),
233                top: px(10),
234            }
235            Children [
236                Text("Move with arrow keys.")
237            ]
238            --
239            Node {
240                position_type: PositionType::Absolute,
241                left: px(10),
242                bottom: px(10),
243                padding: px(5),
244                justify_content: JustifyContent::Center,
245                align_items: AlignItems::Center,
246            }
247            Button
248            Hovered::default()
249            BackgroundColor(NORMAL_BUTTON)
250            on(|event: On<Add<Pressed>>,
251                mut commands: Commands| {
252                    commands.entity(event.entity).insert(BackgroundColor(PRESSED_BUTTON));
253            })
254            on(|event: On<Remove<Pressed>>,
255                is_hovered: Query<&Hovered>,
256                mut commands: Commands| {
257                    if is_hovered.get(event.entity).is_ok_and(Hovered::get) {
258                        commands.entity(event.entity).insert(BackgroundColor(HOVERED_BUTTON));
259                    } else {
260                        commands.entity(event.entity).insert(BackgroundColor(NORMAL_BUTTON));
261                    }
262            })
263            Children [
264                Text("Restart Game")
265                TextFont {
266                        font_size: FontSize::Px(33.0),
267                }
268                TextColor(Color::srgb(0.9, 0.9, 0.9))
269            ]
270        ]
271    });
272    info!("Setup game");
273}
274
275fn teardown_game(mut commands: Commands, player: Single<Entity, With<Sprite>>) {
276    commands.entity(*player).despawn();
277    info!("Teardown game");
278}
279
280#[derive(Resource)]
281struct MenuData {
282    pub button_entity: Entity,
283}
284
285const NORMAL_BUTTON: Color = Color::srgb(0.15, 0.15, 0.15);
286const HOVERED_BUTTON: Color = Color::srgb(0.25, 0.25, 0.25);
287const PRESSED_BUTTON: Color = Color::srgb(0.35, 0.75, 0.35);
288
289fn setup_menu(mut commands: Commands) {
290    let button_entity = commands
291        .spawn((
292            Node {
293                // center button
294                width: percent(100),
295                height: percent(100),
296                justify_content: JustifyContent::Center,
297                align_items: AlignItems::Center,
298                ..default()
299            },
300            children![(
301                Button,
302                ActivateOnPress,
303                Hovered::default(),
304                Node {
305                    width: px(150),
306                    height: px(65),
307                    // horizontally center child text
308                    justify_content: JustifyContent::Center,
309                    // vertically center child text
310                    align_items: AlignItems::Center,
311                    ..default()
312                },
313                BackgroundColor(NORMAL_BUTTON),
314                children![(
315                    Text::new("Play"),
316                    TextFont {
317                        font_size: FontSize::Px(33.0),
318                        ..default()
319                    },
320                    TextColor(Color::srgb(0.9, 0.9, 0.9)),
321                )]
322            )],
323        ))
324        .id();
325    commands.insert_resource(MenuData { button_entity });
326}