states/
states.rs

1//! This example illustrates how to use [`States`] for high-level app control flow.
2//! States are a powerful but intuitive tool for controlling which logic runs when.
3//! You can have multiple independent states, and the [`OnEnter`] and [`OnExit`] schedules
4//! can be used to great effect to ensure that you handle setup and teardown appropriately.
5//!
6//! In this case, we're transitioning from a `Menu` state to an `InGame` state.
7
8use bevy::{dev_tools::states::*, prelude::*};
9
10fn main() {
11    App::new()
12        .add_plugins(DefaultPlugins)
13        .init_state::<AppState>() // Alternatively we could use .insert_state(AppState::Menu)
14        .add_systems(Startup, setup)
15        // This system runs when we enter `AppState::Menu`, during the `StateTransition` schedule.
16        // All systems from the exit schedule of the state we're leaving are run first,
17        // and then all systems from the enter schedule of the state we're entering are run second.
18        .add_systems(OnEnter(AppState::Menu), setup_menu)
19        // By contrast, update systems are stored in the `Update` schedule. They simply
20        // check the value of the `State<T>` resource to see if they should run each frame.
21        .add_systems(Update, menu.run_if(in_state(AppState::Menu)))
22        .add_systems(OnExit(AppState::Menu), cleanup_menu)
23        .add_systems(OnEnter(AppState::InGame), setup_game)
24        .add_systems(
25            Update,
26            (movement, change_color).run_if(in_state(AppState::InGame)),
27        )
28        .add_systems(Update, log_transitions::<AppState>)
29        .run();
30}
31
32#[derive(Debug, Clone, Copy, Default, Eq, PartialEq, Hash, States)]
33enum AppState {
34    #[default]
35    Menu,
36    InGame,
37}
38
39#[derive(Resource)]
40struct MenuData {
41    button_entity: Entity,
42}
43
44const NORMAL_BUTTON: Color = Color::srgb(0.15, 0.15, 0.15);
45const HOVERED_BUTTON: Color = Color::srgb(0.25, 0.25, 0.25);
46const PRESSED_BUTTON: Color = Color::srgb(0.35, 0.75, 0.35);
47
48fn setup(mut commands: Commands) {
49    commands.spawn(Camera2d);
50}
51
52fn setup_menu(mut commands: Commands) {
53    let button_entity = commands
54        .spawn((
55            Node {
56                // center button
57                width: percent(100),
58                height: percent(100),
59                justify_content: JustifyContent::Center,
60                align_items: AlignItems::Center,
61                ..default()
62            },
63            children![(
64                Button,
65                Node {
66                    width: px(150),
67                    height: px(65),
68                    // horizontally center child text
69                    justify_content: JustifyContent::Center,
70                    // vertically center child text
71                    align_items: AlignItems::Center,
72                    ..default()
73                },
74                BackgroundColor(NORMAL_BUTTON),
75                children![(
76                    Text::new("Play"),
77                    TextFont {
78                        font_size: 33.0,
79                        ..default()
80                    },
81                    TextColor(Color::srgb(0.9, 0.9, 0.9)),
82                )],
83            )],
84        ))
85        .id();
86    commands.insert_resource(MenuData { button_entity });
87}
88
89fn menu(
90    mut next_state: ResMut<NextState<AppState>>,
91    mut interaction_query: Query<
92        (&Interaction, &mut BackgroundColor),
93        (Changed<Interaction>, With<Button>),
94    >,
95) {
96    for (interaction, mut color) in &mut interaction_query {
97        match *interaction {
98            Interaction::Pressed => {
99                *color = PRESSED_BUTTON.into();
100                next_state.set(AppState::InGame);
101            }
102            Interaction::Hovered => {
103                *color = HOVERED_BUTTON.into();
104            }
105            Interaction::None => {
106                *color = NORMAL_BUTTON.into();
107            }
108        }
109    }
110}
111
112fn cleanup_menu(mut commands: Commands, menu_data: Res<MenuData>) {
113    commands.entity(menu_data.button_entity).despawn();
114}
115
116fn setup_game(mut commands: Commands, asset_server: Res<AssetServer>) {
117    commands.spawn(Sprite::from_image(asset_server.load("branding/icon.png")));
118}
119
120const SPEED: f32 = 100.0;
121fn movement(
122    time: Res<Time>,
123    input: Res<ButtonInput<KeyCode>>,
124    mut query: Query<&mut Transform, With<Sprite>>,
125) {
126    for mut transform in &mut query {
127        let mut direction = Vec3::ZERO;
128        if input.pressed(KeyCode::ArrowLeft) {
129            direction.x -= 1.0;
130        }
131        if input.pressed(KeyCode::ArrowRight) {
132            direction.x += 1.0;
133        }
134        if input.pressed(KeyCode::ArrowUp) {
135            direction.y += 1.0;
136        }
137        if input.pressed(KeyCode::ArrowDown) {
138            direction.y -= 1.0;
139        }
140
141        if direction != Vec3::ZERO {
142            transform.translation += direction.normalize() * SPEED * time.delta_secs();
143        }
144    }
145}
146
147fn change_color(time: Res<Time>, mut query: Query<&mut Sprite>) {
148    for mut sprite in &mut query {
149        let new_color = LinearRgba {
150            blue: ops::sin(time.elapsed_secs() * 0.5) + 2.0,
151            ..LinearRgba::from(sprite.color)
152        };
153
154        sprite.color = new_color.into();
155    }
156}