Latest commit 9effc3e
use bevy::{log::info, prelude::*}; /// 演示了在系统内部用Timer资源计时并处理Timer资源的状态 fn main() { App::new() .add_plugins(DefaultPlugins) .init_resource::<Countdown>() .add_startup_system(setup_system) .add_system(countdown_system) .add_system(timer_system) .run(); } pub struct Countdown { pub percent_trigger: Timer, pub main_timer: Timer, } impl Countdown { pub fn new() -> Self { Self { percent_trigger: Timer::from_seconds(4.0, true), main_timer: Timer::from_seconds(20.0, false), } } } impl Default for Countdown { fn default() -> Self { Self::new() } } fn setup_system(mut commands: Commands) { // 把一个带有Timer组件的实体添加到World: commands.spawn().insert(Timer::from_seconds(5.0, false)); } /// 这个系统用“Time”资源在场景内的实体上标记所有的“Timer”组件,以获得每次更新之间的增量 fn timer_system( time: Res<Time>, mut query: Query<&mut Timer>, ) { for mut timer in query.iter_mut() { if timer.tick(time.delta()).just_finished() { info!("实体的计时器已结束。"); } } } /// 这个系统控制倒计时资源内的计时器并处理其状态 fn countdown_system(time: Res<Time>, mut countdown: ResMut<Countdown>) { countdown.main_timer.tick(time.delta()); // API鼓励这种计时器状态检查(如果只检查一个值) // 此外,`finished()'与'just_finished'做相同的事情,因为计时器正在重复,但这在视觉上更有意义 if countdown.percent_trigger.tick(time.delta()).just_finished() { if !countdown.main_timer.finished() { // 打印主计时器的完成百分比: info!("计时器已完成{}%。", countdown.main_timer.percent() * 100.0); } else { // 计时器已经结束,暂停输出信息: countdown.percent_trigger.pause(); info!("暂停计时器。"); } } }