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-04-28 09:31:01 +00:00
|
|
|
.add_resource(EventTriggerState::default())
|
|
|
|
.add_resource_init::<EventListenerState>()
|
|
|
|
.add_system(into_resource_system("event_trigger", event_trigger_system))
|
|
|
|
.add_system(into_resource_system(
|
|
|
|
"event_listener",
|
|
|
|
event_listener_system,
|
|
|
|
))
|
2020-03-30 06:51:13 +00:00
|
|
|
.run();
|
|
|
|
}
|
|
|
|
|
2020-04-28 09:31:01 +00:00
|
|
|
struct MyEvent {
|
|
|
|
pub message: String,
|
|
|
|
}
|
|
|
|
|
|
|
|
#[derive(Default)]
|
|
|
|
struct EventTriggerState {
|
|
|
|
elapsed: f32,
|
|
|
|
}
|
|
|
|
|
2020-04-07 04:32:19 +00:00
|
|
|
// sends MyEvent every second
|
2020-04-28 09:31:01 +00:00
|
|
|
fn event_trigger_system(
|
|
|
|
(state, my_events, time): &mut (
|
|
|
|
ResourceMut<EventTriggerState>,
|
|
|
|
ResourceMut<Events<MyEvent>>,
|
|
|
|
Resource<Time>,
|
|
|
|
),
|
|
|
|
) {
|
|
|
|
state.elapsed += time.delta_seconds;
|
|
|
|
if state.elapsed > 1.0 {
|
|
|
|
my_events.send(MyEvent {
|
|
|
|
message: "Hello World".to_string(),
|
|
|
|
});
|
|
|
|
|
|
|
|
state.elapsed = 0.0;
|
|
|
|
}
|
2020-03-30 06:51:13 +00:00
|
|
|
}
|
|
|
|
|
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
|
|
|
|
|
|
|
impl From<&mut Resources> for EventListenerState {
|
|
|
|
fn from(resources: &mut Resources) -> Self {
|
|
|
|
EventListenerState {
|
|
|
|
my_event_reader: resources.get_event_reader::<MyEvent>(),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// prints events as they come in
|
|
|
|
fn event_listener_system(
|
|
|
|
(state, my_events): &mut (ResourceMut<EventListenerState>, Resource<Events<MyEvent>>),
|
|
|
|
) {
|
|
|
|
for my_event in my_events.iter(&mut state.my_event_reader) {
|
|
|
|
println!("{}", my_event.message);
|
|
|
|
}
|
|
|
|
}
|