Skip to main content

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::prelude::*;
9
10fn main() {
11    let mut app = App::new();
12    app.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
29    #[cfg(feature = "bevy_dev_tools")]
30    app.add_systems(Update, bevy::dev_tools::states::log_transitions::<AppState>);
31    #[cfg(not(feature = "bevy_dev_tools"))]
32    warn!("Enable feature bevy_dev_tools to log state transitions");
33
34    app.run();
35}
36
37#[derive(Debug, Clone, Copy, Default, Eq, PartialEq, Hash, States)]
38enum AppState {
39    #[default]
40    Menu,
41    InGame,
42}
43
44#[derive(Resource)]
45struct MenuData {
46    button_entity: Entity,
47}
48
49const NORMAL_BUTTON: Color = Color::srgb(0.15, 0.15, 0.15);
50const HOVERED_BUTTON: Color = Color::srgb(0.25, 0.25, 0.25);
51const PRESSED_BUTTON: Color = Color::srgb(0.35, 0.75, 0.35);
52
53fn setup(mut commands: Commands) {
54    commands.spawn(Camera2d);
55}
56
57fn setup_menu(mut commands: Commands) {
58    let button_entity = commands
59        .spawn((
60            Node {
61                // center button
62                width: percent(100),
63                height: percent(100),
64                justify_content: JustifyContent::Center,
65                align_items: AlignItems::Center,
66                ..default()
67            },
68            children![(
69                Button,
70                Node {
71                    width: px(150),
72                    height: px(65),
73                    // horizontally center child text
74                    justify_content: JustifyContent::Center,
75                    // vertically center child text
76                    align_items: AlignItems::Center,
77                    ..default()
78                },
79                BackgroundColor(NORMAL_BUTTON),
80                children![(
81                    Text::new("Play"),
82                    TextFont {
83                        font_size: FontSize::Px(33.0),
84                        ..default()
85                    },
86                    TextColor(Color::srgb(0.9, 0.9, 0.9)),
87                )],
88            )],
89        ))
90        .id();
91    commands.insert_resource(MenuData { button_entity });
92}
93
94fn menu(
95    mut next_state: ResMut<NextState<AppState>>,
96    mut interaction_query: Query<
97        (&Interaction, &mut BackgroundColor),
98        (Changed<Interaction>, With<Button>),
99    >,
100) {
101    for (interaction, mut color) in &mut interaction_query {
102        match *interaction {
103            Interaction::Pressed => {
104                *color = PRESSED_BUTTON.into();
105                next_state.set(AppState::InGame);
106            }
107            Interaction::Hovered => {
108                *color = HOVERED_BUTTON.into();
109            }
110            Interaction::None => {
111                *color = NORMAL_BUTTON.into();
112            }
113        }
114    }
115}
116
117fn cleanup_menu(mut commands: Commands, menu_data: Res<MenuData>) {
118    commands.entity(menu_data.button_entity).despawn();
119}
120
121fn setup_game(mut commands: Commands, asset_server: Res<AssetServer>) {
122    commands.spawn(Sprite::from_image(asset_server.load("branding/icon.png")));
123}
124
125const SPEED: f32 = 100.0;
126fn movement(
127    time: Res<Time>,
128    input: Res<ButtonInput<KeyCode>>,
129    mut query: Query<&mut Transform, With<Sprite>>,
130) {
131    for mut transform in &mut query {
132        let mut direction = Vec3::ZERO;
133        if input.pressed(KeyCode::ArrowLeft) {
134            direction.x -= 1.0;
135        }
136        if input.pressed(KeyCode::ArrowRight) {
137            direction.x += 1.0;
138        }
139        if input.pressed(KeyCode::ArrowUp) {
140            direction.y += 1.0;
141        }
142        if input.pressed(KeyCode::ArrowDown) {
143            direction.y -= 1.0;
144        }
145
146        if direction != Vec3::ZERO {
147            transform.translation += direction.normalize() * SPEED * time.delta_secs();
148        }
149    }
150}
151
152fn change_color(time: Res<Time>, mut query: Query<&mut Sprite>) {
153    for mut sprite in &mut query {
154        let new_color = LinearRgba {
155            blue: ops::sin(time.elapsed_secs() * 0.5) + 2.0,
156            ..LinearRgba::from(sprite.color)
157        };
158
159        sprite.color = new_color.into();
160    }
161}