use bevy::prelude::*;
#[derive(Debug, Default, Clone, Copy, Eq, PartialEq, Hash)]
enum AppState {
#[default]
MainMenu,
InGame,
}
impl States for AppState {
type Iter = std::array::IntoIter<AppState, 2>;
fn variants() -> Self::Iter {
[AppState::MainMenu, AppState::InGame].into_iter()
}
}
#[derive(Component)]
struct TextToPrint(String);
#[derive(Component, Deref, DerefMut)]
struct PrinterTick(Timer);
#[derive(Component)]
struct MenuClose;
#[derive(Component)]
struct LevelUnload;
fn main() {
App::new()
.add_plugins(DefaultPlugins)
.add_state::<AppState>()
.add_system(setup_system.on_startup())
.add_system(print_text_system)
.add_system(transition_to_in_game_system.in_set(OnUpdate(AppState::MainMenu)))
.add_systems((
cleanup_system::<MenuClose>.in_schedule(OnExit(AppState::MainMenu)),
cleanup_system::<LevelUnload>.in_schedule(OnExit(AppState::InGame)),
))
.run();
}
fn setup_system(mut commands: Commands) {
commands.spawn((
PrinterTick(Timer::from_seconds(1.0, TimerMode::Repeating)),
TextToPrint("I will print until you press space.".to_string()),
MenuClose,
));
commands.spawn((
PrinterTick(Timer::from_seconds(1.0, TimerMode::Repeating)),
TextToPrint("I will always print".to_string()),
LevelUnload,
));
}
fn print_text_system(time: Res<Time>, mut query: Query<(&mut PrinterTick, &TextToPrint)>) {
for (mut timer, text) in &mut query {
if timer.tick(time.delta()).just_finished() {
info!("{}", text.0);
}
}
}
fn transition_to_in_game_system(
mut next_state: ResMut<NextState<AppState>>,
keyboard_input: Res<Input<KeyCode>>,
) {
if keyboard_input.pressed(KeyCode::Space) {
next_state.set(AppState::InGame);
}
}
fn cleanup_system<T: Component>(mut commands: Commands, query: Query<Entity, With<T>>) {
for e in &query {
commands.entity(e).despawn_recursive();
}
}