From 5de4b0bac3d08a04d1e16725329c07416dca3d43 Mon Sep 17 00:00:00 2001 From: hut Date: Fri, 5 Apr 2024 21:27:19 +0200 Subject: [PATCH] move targeting code into an event handler --- src/hud.rs | 57 ++++++++++++++++++++++++++++++++++++++---------------- 1 file changed, 40 insertions(+), 17 deletions(-) diff --git a/src/hud.rs b/src/hud.rs index 95a57a0..467c593 100644 --- a/src/hud.rs +++ b/src/hud.rs @@ -21,16 +21,23 @@ pub struct HudPlugin; impl Plugin for HudPlugin { fn build(&self, app: &mut App) { app.add_systems(Startup, setup); - app.add_systems(Update, (update, handle_input)); + app.add_systems(Update, ( + update, + handle_input, + handle_target_event, + update_target_selectagon, + )); app.insert_resource(Log { logs: VecDeque::with_capacity(LOG_MAX), needs_rerendering: true, }); app.insert_resource(FPSUpdateTimer( Timer::from_seconds(HUD_REFRESH_TIME, TimerMode::Repeating))); + app.add_event::(); } } +#[derive(Event)] pub struct TargetEvent(pub Option); #[derive(Component)] struct GaugesText; #[derive(Component)] struct ChatText; #[derive(Component)] struct Reticule; @@ -574,9 +581,9 @@ fn handle_input( mut q_hud: Query<&mut Visibility, With>, mut ew_sfx: EventWriter, mut ew_togglemusic: EventWriter, + mut ew_target: EventWriter, mut ambient_light: ResMut, q_objects: Query<(Entity, &Transform), (With, Without, Without, Without)>, - q_target: Query>, q_camera: Query<&Transform, With>, ) { if keyboard_input.just_pressed(settings.key_togglehud) { @@ -601,24 +608,40 @@ fn handle_input( if let Ok(camtrans) = q_camera.get_single() { let objects: Vec<(Entity, &Transform)> = q_objects.iter().collect(); if let (Some(new_target), _dist) = camera::find_closest_target::(objects, camtrans) { - if let Ok(old_target) = q_target.get_single() { - if old_target != new_target { - commands.entity(old_target).remove::(); - commands.entity(new_target).insert(IsTargeted); - ew_sfx.send(audio::PlaySfxEvent(audio::Sfx::Click)); - } - } - else { - commands.entity(new_target).insert(IsTargeted); - ew_sfx.send(audio::PlaySfxEvent(audio::Sfx::Click)); - } + ew_target.send(TargetEvent(Some(new_target))); } else { - for entity in &q_target { - commands.entity(entity).remove::(); - ew_sfx.send(audio::PlaySfxEvent(audio::Sfx::Click)); - } + ew_target.send(TargetEvent(None)); } } } } + +fn handle_target_event( + mut commands: Commands, + settings: Res, + mut er_target: EventReader, + mut ew_sfx: EventWriter, + q_target: Query>, +) { + let mut play_sfx = false; + + for TargetEvent(target) in er_target.read() { + for old_target in &q_target { + commands.entity(old_target).remove::(); + play_sfx = true; + } + if let Some(entity) = target { + commands.entity(*entity).insert(IsTargeted); + play_sfx = true; + } + if play_sfx && !settings.mute_sfx { + ew_sfx.send(audio::PlaySfxEvent(audio::Sfx::Click)); + } + break; // Only accept a single event per frame + } +} + +fn update_target_selectagon( +) { +}