| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
use bevy::prelude::*; |
| 13 |
|
| 14 |
#[derive(Debug, Default, Clone, Copy, Eq, PartialEq, Hash, States)] |
| 15 |
enum AppState { |
| 16 |
#[default] |
| 17 |
MainMenu, |
| 18 |
InGame, |
| 19 |
} |
| 20 |
|
| 21 |
#[derive(Component)] |
| 22 |
struct TextToPrint(String); |
| 23 |
|
| 24 |
#[derive(Component, Deref, DerefMut)] |
| 25 |
struct PrinterTick(Timer); |
| 26 |
|
| 27 |
#[derive(Component)] |
| 28 |
struct MenuClose; |
| 29 |
|
| 30 |
#[derive(Component)] |
| 31 |
struct LevelUnload; |
| 32 |
|
| 33 |
fn main() { |
| 34 |
App::new() |
| 35 |
.add_plugins(DefaultPlugins) |
| 36 |
.init_state::<AppState>() |
| 37 |
.add_systems(Startup, setup_system) |
| 38 |
.add_systems( |
| 39 |
Update, |
| 40 |
( |
| 41 |
print_text_system, |
| 42 |
transition_to_in_game_system.run_if(in_state(AppState::MainMenu)), |
| 43 |
), |
| 44 |
) |
| 45 |
|
| 46 |
|
| 47 |
.add_systems(OnExit(AppState::MainMenu), cleanup_system::<MenuClose>) |
| 48 |
.add_systems(OnExit(AppState::InGame), cleanup_system::<LevelUnload>) |
| 49 |
.run(); |
| 50 |
} |
| 51 |
|
| 52 |
fn setup_system(mut commands: Commands) { |
| 53 |
commands.spawn(( |
| 54 |
PrinterTick(Timer::from_seconds(1.0, TimerMode::Repeating)), |
| 55 |
TextToPrint("I will print until you press space.".to_string()), |
| 56 |
MenuClose, |
| 57 |
)); |
| 58 |
|
| 59 |
commands.spawn(( |
| 60 |
PrinterTick(Timer::from_seconds(1.0, TimerMode::Repeating)), |
| 61 |
TextToPrint("I will always print".to_string()), |
| 62 |
LevelUnload, |
| 63 |
)); |
| 64 |
} |
| 65 |
|
| 66 |
fn print_text_system(time: Res<Time>, mut query: Query<(&mut PrinterTick, &TextToPrint)>) { |
| 67 |
for (mut timer, text) in &mut query { |
| 68 |
if timer.tick(time.delta()).just_finished() { |
| 69 |
info!("{}", text.0); |
| 70 |
} |
| 71 |
} |
| 72 |
} |
| 73 |
|
| 74 |
fn transition_to_in_game_system( |
| 75 |
mut next_state: ResMut<NextState<AppState>>, |
| 76 |
keyboard_input: Res<ButtonInput<KeyCode>>, |
| 77 |
) { |
| 78 |
if keyboard_input.pressed(KeyCode::Space) { |
| 79 |
next_state.set(AppState::InGame); |
| 80 |
} |
| 81 |
} |
| 82 |
|
| 83 |
|
| 84 |
|
| 85 |
fn cleanup_system<T: Component>(mut commands: Commands, query: Query<Entity, With<T>>) { |
| 86 |
for e in &query { |
| 87 |
commands.entity(e).despawn(); |
| 88 |
} |
| 89 |
} |