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