2020-03-30 06:51:13 +00:00
|
|
|
use bevy::prelude::*;
|
|
|
|
|
|
|
|
fn main() {
|
|
|
|
App::build()
|
2020-04-04 19:40:32 +00:00
|
|
|
.add_default_plugins()
|
2020-03-30 06:51:13 +00:00
|
|
|
.add_event::<MyEvent>()
|
2020-05-13 23:35:38 +00:00
|
|
|
.init_resource::<EventTriggerState>()
|
2020-05-01 20:12:47 +00:00
|
|
|
.init_resource::<EventListenerState>()
|
2020-04-30 19:22:35 +00:00
|
|
|
.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 {
|
2020-06-04 03:08:20 +00:00
|
|
|
event_timer: Timer::from_seconds(1.0),
|
2020-06-04 02:53:41 +00:00
|
|
|
}
|
|
|
|
}
|
2020-04-28 09:31:01 +00:00
|
|
|
}
|
|
|
|
|
2020-04-07 04:32:19 +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
|
|
|
) {
|
2020-06-04 02:53:41 +00:00
|
|
|
state.event_timer.tick(time.delta_seconds);
|
|
|
|
if state.event_timer.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-06-04 03:08:20 +00:00
|
|
|
|
2020-06-04 02:53:41 +00:00
|
|
|
state.event_timer.reset();
|
2020-04-28 09:31:01 +00:00
|
|
|
}
|
2020-03-30 06:51:13 +00:00
|
|
|
}
|
|
|
|
|
2020-06-04 06:53:00 +00:00
|
|
|
#[derive(Default)]
|
2020-04-28 09:31:01 +00:00
|
|
|
struct EventListenerState {
|
|
|
|
my_event_reader: EventReader<MyEvent>,
|
2020-03-30 06:51:13 +00:00
|
|
|
}
|
2020-04-28 09:31:01 +00:00
|
|
|
|
|
|
|
// prints events as they come in
|
2020-05-14 01:05:18 +00:00
|
|
|
fn event_listener_system(mut state: ResMut<EventListenerState>, my_events: Res<Events<MyEvent>>) {
|
2020-04-28 17:59:42 +00:00
|
|
|
for my_event in state.my_event_reader.iter(&my_events) {
|
2020-04-28 09:31:01 +00:00
|
|
|
println!("{}", my_event.message);
|
|
|
|
}
|
2020-04-28 09:52:26 +00:00
|
|
|
}
|