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() {
|
2021-07-27 20:21:06 +00:00
|
|
|
App::new()
|
2020-11-03 03:01:17 +00:00
|
|
|
.add_plugins(DefaultPlugins)
|
2020-03-30 06:51:13 +00:00
|
|
|
.add_event::<MyEvent>()
|
2022-02-04 01:24:47 +00:00
|
|
|
.add_event::<PlaySound>()
|
2020-05-13 23:35:38 +00:00
|
|
|
.init_resource::<EventTriggerState>()
|
2022-02-04 01:24:47 +00:00
|
|
|
.add_system(event_trigger)
|
|
|
|
.add_system(event_listener)
|
|
|
|
.add_system(sound_player)
|
2020-03-30 06:51:13 +00:00
|
|
|
.run();
|
|
|
|
}
|
|
|
|
|
2020-04-28 09:31:01 +00:00
|
|
|
struct MyEvent {
|
|
|
|
pub message: String,
|
|
|
|
}
|
|
|
|
|
2022-02-04 01:24:47 +00:00
|
|
|
#[derive(Default)]
|
|
|
|
struct PlaySound;
|
|
|
|
|
2020-04-28 09:31:01 +00:00
|
|
|
struct EventTriggerState {
|
2020-06-04 02:53:41 +00:00
|
|
|
event_timer: Timer,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Default for EventTriggerState {
|
|
|
|
fn default() -> Self {
|
|
|
|
EventTriggerState {
|
2020-08-21 21:57:25 +00:00
|
|
|
event_timer: Timer::from_seconds(1.0, true),
|
2020-06-04 02:53:41 +00:00
|
|
|
}
|
|
|
|
}
|
2020-04-28 09:31:01 +00:00
|
|
|
}
|
|
|
|
|
2022-02-04 01:24:47 +00:00
|
|
|
// sends MyEvent and PlaySound every second
|
|
|
|
fn event_trigger(
|
2020-06-04 02:53:41 +00:00
|
|
|
time: Res<Time>,
|
2020-05-14 00:52:47 +00:00
|
|
|
mut state: ResMut<EventTriggerState>,
|
2021-03-07 20:42:04 +00:00
|
|
|
mut my_events: EventWriter<MyEvent>,
|
2022-02-04 01:24:47 +00:00
|
|
|
mut play_sound_events: EventWriter<PlaySound>,
|
2020-04-28 09:31:01 +00:00
|
|
|
) {
|
2021-03-05 19:59:14 +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
|
|
|
});
|
2022-02-04 01:24:47 +00:00
|
|
|
play_sound_events.send_default();
|
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
|
2022-02-04 01:24:47 +00:00
|
|
|
fn event_listener(mut events: EventReader<MyEvent>) {
|
2021-01-19 06:23:30 +00:00
|
|
|
for my_event in events.iter() {
|
2021-04-22 23:30:48 +00:00
|
|
|
info!("{}", my_event.message);
|
2020-04-28 09:31:01 +00:00
|
|
|
}
|
2020-04-28 09:52:26 +00:00
|
|
|
}
|
2022-02-04 01:24:47 +00:00
|
|
|
|
|
|
|
fn sound_player(mut play_sound_events: EventReader<PlaySound>) {
|
|
|
|
for _ in play_sound_events.iter() {
|
|
|
|
info!("Playing a sound");
|
|
|
|
}
|
|
|
|
}
|