use bevy::prelude::*;
use pecs::prelude::*;
fn main() {
App::new()
.add_plugins(DefaultPlugins)
.add_plugins(PecsPlugin)
.add_systems(Startup, setup)
.add_systems(Update, process_timers_system)
.run();
}
#[derive(Component)]
pub struct MyTimer(PromiseId, f32);
pub fn delay(duration: f32) -> Promise<(), ()> {
Promise::register(
move |world, id| {
let now = world.resource::<Time>().elapsed_seconds();
world.spawn(MyTimer(id, now + duration));
},
move |world, id| {
let entity = {
let mut timers = world.query::<(Entity, &MyTimer)>();
timers
.iter(world)
.filter(|(_entity, timer)| timer.0 == id)
.map(|(entity, _timer)| entity)
.next()
};
if let Some(entity) = entity {
world.despawn(entity);
}
},
)
}
pub fn process_timers_system(timers: Query<(Entity, &MyTimer)>, mut commands: Commands, time: Res<Time>) {
let now = time.elapsed_seconds();
for (entity, timer) in timers.iter().filter(|(_, t)| t.1 < now) {
let promise_id = timer.0;
commands.promise(promise_id).resolve(());
commands.entity(entity).despawn();
}
}
fn setup(mut commands: Commands) {
commands
.promise(|| ())
.then(asyn! {
info!("Starting");
delay(1.)
})
.then(asyn! {
info!("Completing");
});
commands.promise(delay(2.)).then(asyn! {
info!("I'm another timer");
asyn::app::exit()
});
}