bevy/examples/ecs/event.rs

50 lines
1.2 KiB
Rust
Raw Normal View History

2020-03-30 06:51:13 +00:00
use bevy::prelude::*;
2020-07-28 20:43:07 +00:00
/// 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.
2020-03-30 06:51:13 +00:00
fn main() {
App::build()
.add_plugins(DefaultPlugins)
2020-03-30 06:51:13 +00:00
.add_event::<MyEvent>()
2020-05-13 23:35:38 +00:00
.init_resource::<EventTriggerState>()
.add_system(event_trigger_system.system())
.add_system(event_listener_system.system())
2020-03-30 06:51:13 +00:00
.run();
}
2020-04-28 09:31:01 +00:00
struct MyEvent {
pub message: String,
}
struct EventTriggerState {
2020-06-04 02:53:41 +00:00
event_timer: Timer,
}
impl Default for EventTriggerState {
fn default() -> Self {
EventTriggerState {
event_timer: Timer::from_seconds(1.0, true),
2020-06-04 02:53:41 +00:00
}
}
2020-04-28 09:31:01 +00:00
}
// sends MyEvent every second
2020-04-28 09:31:01 +00:00
fn event_trigger_system(
2020-06-04 02:53:41 +00:00
time: Res<Time>,
2020-05-14 00:52:47 +00:00
mut state: ResMut<EventTriggerState>,
mut my_events: ResMut<Events<MyEvent>>,
2020-04-28 09:31:01 +00:00
) {
if state.event_timer.tick(time.delta()).finished() {
2020-04-28 09:31:01 +00:00
my_events.send(MyEvent {
2020-05-01 20:12:47 +00:00
message: "MyEvent just happened!".to_string(),
2020-04-28 09:31:01 +00:00
});
}
2020-03-30 06:51:13 +00:00
}
2020-04-28 09:31:01 +00:00
// prints events as they come in
fn event_listener_system(mut events: EventReader<MyEvent>) {
for my_event in events.iter() {
2020-04-28 09:31:01 +00:00
println!("{}", my_event.message);
}
}