mirror of
https://github.com/bevyengine/bevy
synced 2024-11-14 17:07:47 +00:00
ab407aa697
This pull request is following the discussion on the issue #1127. Additionally, it integrates the change proposed by #1112. The list of change of this pull request: * ✨ Add `Timer::times_finished` method that counts the number of wraps for repeating timers. * ♻️ Refactored `Timer` * 🐛 Fix a bug where 2 successive calls to `Timer::tick` which makes a repeating timer to finish makes `Timer::just_finished` to return `false` where it should return `true`. Minimal failing example: ```rust use bevy::prelude::*; let mut timer: Timer<()> = Timer::from_seconds(1.0, true); timer.tick(1.5); assert!(timer.finished()); assert!(timer.just_finished()); timer.tick(1.5); assert!(timer.finished()); assert!(timer.just_finished()); // <- This fails where it should not ``` * 📚 Add extensive documentation for Timer with doc examples. * ✨ Add a `Stopwatch` struct similar to `Timer` with extensive doc and tests. Even if the type specialization is not retained for bevy, the doc, bugfix and added method are worth salvaging 😅. This is my first PR for bevy, please be kind to me ❤️ . Co-authored-by: Carter Anderson <mcanders1@gmail.com>
49 lines
1.2 KiB
Rust
49 lines
1.2 KiB
Rust
use bevy::prelude::*;
|
|
|
|
/// This example creates a new event, a system that triggers the event once per second,
|
|
/// and a system that prints a message whenever the event is received.
|
|
fn main() {
|
|
App::build()
|
|
.add_plugins(DefaultPlugins)
|
|
.add_event::<MyEvent>()
|
|
.init_resource::<EventTriggerState>()
|
|
.add_system(event_trigger_system.system())
|
|
.add_system(event_listener_system.system())
|
|
.run();
|
|
}
|
|
|
|
struct MyEvent {
|
|
pub message: String,
|
|
}
|
|
|
|
struct EventTriggerState {
|
|
event_timer: Timer,
|
|
}
|
|
|
|
impl Default for EventTriggerState {
|
|
fn default() -> Self {
|
|
EventTriggerState {
|
|
event_timer: Timer::from_seconds(1.0, true),
|
|
}
|
|
}
|
|
}
|
|
|
|
// sends MyEvent every second
|
|
fn event_trigger_system(
|
|
time: Res<Time>,
|
|
mut state: ResMut<EventTriggerState>,
|
|
mut my_events: ResMut<Events<MyEvent>>,
|
|
) {
|
|
if state.event_timer.tick(time.delta()).finished() {
|
|
my_events.send(MyEvent {
|
|
message: "MyEvent just happened!".to_string(),
|
|
});
|
|
}
|
|
}
|
|
|
|
// prints events as they come in
|
|
fn event_listener_system(mut events: EventReader<MyEvent>) {
|
|
for my_event in events.iter() {
|
|
println!("{}", my_event.message);
|
|
}
|
|
}
|