pub fn in_state<S>(state: S) -> impl FnMut(Option<Res<'_, State<S>>>) + Clonewhere
S: States,
Expand description
Generates a Condition
-satisfying closure that returns true
if the state machine is currently in state
.
Will return false
if the state does not exist or if not in state
.
§Example
#[derive(States, Clone, Copy, Default, Eq, PartialEq, Hash, Debug)]
enum GameState {
#[default]
Playing,
Paused,
}
world.init_resource::<State<GameState>>();
app.add_systems((
// `in_state` will only return true if the
// given state equals the given value
play_system.run_if(in_state(GameState::Playing)),
pause_system.run_if(in_state(GameState::Paused)),
));
fn play_system(mut counter: ResMut<Counter>) {
counter.0 += 1;
}
fn pause_system(mut counter: ResMut<Counter>) {
counter.0 -= 1;
}
// We default to `GameState::Playing` so `play_system` runs
app.run(&mut world);
assert_eq!(world.resource::<Counter>().0, 1);
*world.resource_mut::<State<GameState>>() = State::new(GameState::Paused);
// Now that we are in `GameState::Pause`, `pause_system` will run
app.run(&mut world);
assert_eq!(world.resource::<Counter>().0, 0);
Examples found in repository?
More examples
examples/games/game_menu.rs (line 60)
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292
pub fn splash_plugin(app: &mut App) {
// As this plugin is managing the splash screen, it will focus on the state `GameState::Splash`
app
// When entering the state, spawn everything needed for this screen
.add_systems(OnEnter(GameState::Splash), splash_setup)
// While in this state, run the `countdown` system
.add_systems(Update, countdown.run_if(in_state(GameState::Splash)))
// When exiting the state, despawn everything that was spawned for this screen
.add_systems(OnExit(GameState::Splash), despawn_screen::<OnSplashScreen>);
}
// Tag component used to tag entities added on the splash screen
#[derive(Component)]
struct OnSplashScreen;
// Newtype to use a `Timer` for this screen as a resource
#[derive(Resource, Deref, DerefMut)]
struct SplashTimer(Timer);
fn splash_setup(mut commands: Commands, asset_server: Res<AssetServer>) {
let icon = asset_server.load("branding/icon.png");
// Display the logo
commands
.spawn((
NodeBundle {
style: Style {
align_items: AlignItems::Center,
justify_content: JustifyContent::Center,
width: Val::Percent(100.0),
height: Val::Percent(100.0),
..default()
},
..default()
},
OnSplashScreen,
))
.with_children(|parent| {
parent.spawn(ImageBundle {
style: Style {
// This will set the logo to be 200px wide, and auto adjust its height
width: Val::Px(200.0),
..default()
},
image: UiImage::new(icon),
..default()
});
});
// Insert the timer as a resource
commands.insert_resource(SplashTimer(Timer::from_seconds(1.0, TimerMode::Once)));
}
// Tick the timer, and change state when finished
fn countdown(
mut game_state: ResMut<NextState<GameState>>,
time: Res<Time>,
mut timer: ResMut<SplashTimer>,
) {
if timer.tick(time.delta()).finished() {
game_state.set(GameState::Menu);
}
}
}
mod game {
use bevy::prelude::*;
use super::{despawn_screen, DisplayQuality, GameState, Volume, TEXT_COLOR};
// This plugin will contain the game. In this case, it's just be a screen that will
// display the current settings for 5 seconds before returning to the menu
pub fn game_plugin(app: &mut App) {
app.add_systems(OnEnter(GameState::Game), game_setup)
.add_systems(Update, game.run_if(in_state(GameState::Game)))
.add_systems(OnExit(GameState::Game), despawn_screen::<OnGameScreen>);
}
// Tag component used to tag entities added on the game screen
#[derive(Component)]
struct OnGameScreen;
#[derive(Resource, Deref, DerefMut)]
struct GameTimer(Timer);
fn game_setup(
mut commands: Commands,
display_quality: Res<DisplayQuality>,
volume: Res<Volume>,
) {
commands
.spawn((
NodeBundle {
style: Style {
width: Val::Percent(100.0),
height: Val::Percent(100.0),
// center children
align_items: AlignItems::Center,
justify_content: JustifyContent::Center,
..default()
},
..default()
},
OnGameScreen,
))
.with_children(|parent| {
// First create a `NodeBundle` for centering what we want to display
parent
.spawn(NodeBundle {
style: Style {
// This will display its children in a column, from top to bottom
flex_direction: FlexDirection::Column,
// `align_items` will align children on the cross axis. Here the main axis is
// vertical (column), so the cross axis is horizontal. This will center the
// children
align_items: AlignItems::Center,
..default()
},
background_color: Color::BLACK.into(),
..default()
})
.with_children(|parent| {
// Display two lines of text, the second one with the current settings
parent.spawn(
TextBundle::from_section(
"Will be back to the menu shortly...",
TextStyle {
font_size: 80.0,
color: TEXT_COLOR,
..default()
},
)
.with_style(Style {
margin: UiRect::all(Val::Px(50.0)),
..default()
}),
);
parent.spawn(
TextBundle::from_sections([
TextSection::new(
format!("quality: {:?}", *display_quality),
TextStyle {
font_size: 60.0,
color: Color::BLUE,
..default()
},
),
TextSection::new(
" - ",
TextStyle {
font_size: 60.0,
color: TEXT_COLOR,
..default()
},
),
TextSection::new(
format!("volume: {:?}", *volume),
TextStyle {
font_size: 60.0,
color: Color::GREEN,
..default()
},
),
])
.with_style(Style {
margin: UiRect::all(Val::Px(50.0)),
..default()
}),
);
});
});
// Spawn a 5 seconds timer to trigger going back to the menu
commands.insert_resource(GameTimer(Timer::from_seconds(5.0, TimerMode::Once)));
}
// Tick the timer, and change state when finished
fn game(
time: Res<Time>,
mut game_state: ResMut<NextState<GameState>>,
mut timer: ResMut<GameTimer>,
) {
if timer.tick(time.delta()).finished() {
game_state.set(GameState::Menu);
}
}
}
mod menu {
use bevy::{app::AppExit, prelude::*};
use super::{despawn_screen, DisplayQuality, GameState, Volume, TEXT_COLOR};
// This plugin manages the menu, with 5 different screens:
// - a main menu with "New Game", "Settings", "Quit"
// - a settings menu with two submenus and a back button
// - two settings screen with a setting that can be set and a back button
pub fn menu_plugin(app: &mut App) {
app
// At start, the menu is not enabled. This will be changed in `menu_setup` when
// entering the `GameState::Menu` state.
// Current screen in the menu is handled by an independent state from `GameState`
.init_state::<MenuState>()
.add_systems(OnEnter(GameState::Menu), menu_setup)
// Systems to handle the main menu screen
.add_systems(OnEnter(MenuState::Main), main_menu_setup)
.add_systems(OnExit(MenuState::Main), despawn_screen::<OnMainMenuScreen>)
// Systems to handle the settings menu screen
.add_systems(OnEnter(MenuState::Settings), settings_menu_setup)
.add_systems(
OnExit(MenuState::Settings),
despawn_screen::<OnSettingsMenuScreen>,
)
// Systems to handle the display settings screen
.add_systems(
OnEnter(MenuState::SettingsDisplay),
display_settings_menu_setup,
)
.add_systems(
Update,
(setting_button::<DisplayQuality>.run_if(in_state(MenuState::SettingsDisplay)),),
)
.add_systems(
OnExit(MenuState::SettingsDisplay),
despawn_screen::<OnDisplaySettingsMenuScreen>,
)
// Systems to handle the sound settings screen
.add_systems(OnEnter(MenuState::SettingsSound), sound_settings_menu_setup)
.add_systems(
Update,
setting_button::<Volume>.run_if(in_state(MenuState::SettingsSound)),
)
.add_systems(
OnExit(MenuState::SettingsSound),
despawn_screen::<OnSoundSettingsMenuScreen>,
)
// Common systems to all screens that handles buttons behavior
.add_systems(
Update,
(menu_action, button_system).run_if(in_state(GameState::Menu)),
);
}
examples/ecs/generic_system.rs (line 42)
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
fn main() {
App::new()
.add_plugins(DefaultPlugins)
.init_state::<AppState>()
.add_systems(Startup, setup_system)
.add_systems(
Update,
(
print_text_system,
transition_to_in_game_system.run_if(in_state(AppState::MainMenu)),
),
)
// Cleanup systems.
// Pass in the types your system should operate on using the ::<T> (turbofish) syntax
.add_systems(OnExit(AppState::MainMenu), cleanup_system::<MenuClose>)
.add_systems(OnExit(AppState::InGame), cleanup_system::<LevelUnload>)
.run();
}
examples/2d/bounding_2d.rs (line 19)
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
fn main() {
App::new()
.add_plugins(DefaultPlugins)
.init_state::<Test>()
.add_systems(Startup, setup)
.add_systems(
Update,
(update_text, spin, update_volumes, update_test_state),
)
.add_systems(
PostUpdate,
(
render_shapes,
(
aabb_intersection_system.run_if(in_state(Test::AabbSweep)),
circle_intersection_system.run_if(in_state(Test::CircleSweep)),
ray_cast_system.run_if(in_state(Test::RayCast)),
aabb_cast_system.run_if(in_state(Test::AabbCast)),
bounding_circle_cast_system.run_if(in_state(Test::CircleCast)),
),
render_volumes,
)
.chain(),
)
.run();
}
examples/games/alien_cake_addict.rs (line 38)
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
fn main() {
App::new()
.add_plugins(DefaultPlugins)
.init_resource::<Game>()
.insert_resource(BonusSpawnTimer(Timer::from_seconds(
5.0,
TimerMode::Repeating,
)))
.init_state::<GameState>()
.add_systems(Startup, setup_cameras)
.add_systems(OnEnter(GameState::Playing), setup)
.add_systems(
Update,
(
move_player,
focus_camera,
rotate_bonus,
scoreboard_system,
spawn_bonus,
)
.run_if(in_state(GameState::Playing)),
)
.add_systems(OnExit(GameState::Playing), teardown)
.add_systems(OnEnter(GameState::GameOver), display_score)
.add_systems(
Update,
(
gameover_keyboard.run_if(in_state(GameState::GameOver)),
bevy::window::close_on_esc,
),
)
.add_systems(OnExit(GameState::GameOver), teardown)
.run();
}
examples/ecs/state.rs (line 21)
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
fn main() {
App::new()
.add_plugins(DefaultPlugins)
.init_state::<AppState>() // Alternatively we could use .insert_state(AppState::Menu)
.add_systems(Startup, setup)
// This system runs when we enter `AppState::Menu`, during the `StateTransition` schedule.
// All systems from the exit schedule of the state we're leaving are run first,
// and then all systems from the enter schedule of the state we're entering are run second.
.add_systems(OnEnter(AppState::Menu), setup_menu)
// By contrast, update systems are stored in the `Update` schedule. They simply
// check the value of the `State<T>` resource to see if they should run each frame.
.add_systems(Update, menu.run_if(in_state(AppState::Menu)))
.add_systems(OnExit(AppState::Menu), cleanup_menu)
.add_systems(OnEnter(AppState::InGame), setup_game)
.add_systems(
Update,
(movement, change_color).run_if(in_state(AppState::InGame)),
)
.add_systems(Update, log_transitions)
.run();
}