Bevy Book: Resources

This commit is contained in:
Danny McGee
2023-09-27 11:46:02 -04:00
parent 4585fdec24
commit 9e66728597
+24 -8
View File
@@ -1,15 +1,20 @@
use std::time::Duration;
use bevy::{ use bevy::{
app::{Startup, Update}, prelude::{App, Commands, Component, Query, Res, ResMut, Resource, Startup, Update, With},
prelude::{App, Commands, Component, Query, With}, time::{Time, TimerMode},
}; };
pub struct Plugin; pub struct Plugin;
impl bevy::app::Plugin for Plugin { impl bevy::app::Plugin for Plugin {
fn build(&self, app: &mut App) { fn build(&self, app: &mut App) {
#[rustfmt::skip] app.insert_resource(Timer(bevy::time::Timer::from_seconds(
app.add_systems(Startup, startup) 2.0,
.add_systems(Update, greet); TimerMode::Repeating,
)))
.add_systems(Startup, startup)
.add_systems(Update, greet);
} }
} }
@@ -25,14 +30,25 @@ impl Name {
} }
} }
#[derive(Resource)]
struct Timer(bevy::time::Timer);
impl Timer {
fn tick(&mut self, delta: Duration) -> &bevy::time::Timer {
self.0.tick(delta)
}
}
fn startup(mut cmds: Commands) { fn startup(mut cmds: Commands) {
cmds.spawn((Person, Name::new("Elaina Proctor"))); cmds.spawn((Person, Name::new("Elaina Proctor")));
cmds.spawn((Person, Name::new("Renzo Hume"))); cmds.spawn((Person, Name::new("Renzo Hume")));
cmds.spawn((Person, Name::new("Zayna Nieves"))); cmds.spawn((Person, Name::new("Zayna Nieves")));
} }
fn greet(q: Query<&Name, With<Person>>) { fn greet(time: Res<Time>, mut timer: ResMut<Timer>, q: Query<&Name, With<Person>>) {
for name in &q { if timer.tick(time.delta()).just_finished() {
println!("Hello, {}!", name.0); for name in &q {
println!("Hello, {}!", name.0);
}
} }
} }