move targeting code into an event handler

This commit is contained in:
yuni 2024-04-05 21:27:19 +02:00
parent b700e0fe24
commit 5de4b0bac3

View file

@ -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::<TargetEvent>();
}
}
#[derive(Event)] pub struct TargetEvent(pub Option<Entity>);
#[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<ToggleableHudElement>>,
mut ew_sfx: EventWriter<audio::PlaySfxEvent>,
mut ew_togglemusic: EventWriter<audio::ToggleMusicEvent>,
mut ew_target: EventWriter<TargetEvent>,
mut ambient_light: ResMut<AmbientLight>,
q_objects: Query<(Entity, &Transform), (With<IsClickable>, Without<IsTargeted>, Without<actor::PlayerDrivesThis>, Without<actor::Player>)>,
q_target: Query<Entity, With<IsTargeted>>,
q_camera: Query<&Transform, With<Camera>>,
) {
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::<Entity>(objects, camtrans) {
if let Ok(old_target) = q_target.get_single() {
if old_target != new_target {
ew_target.send(TargetEvent(Some(new_target)));
}
else {
ew_target.send(TargetEvent(None));
}
}
}
}
fn handle_target_event(
mut commands: Commands,
settings: Res<settings::Settings>,
mut er_target: EventReader<TargetEvent>,
mut ew_sfx: EventWriter<audio::PlaySfxEvent>,
q_target: Query<Entity, With<IsTargeted>>,
) {
let mut play_sfx = false;
for TargetEvent(target) in er_target.read() {
for old_target in &q_target {
commands.entity(old_target).remove::<IsTargeted>();
commands.entity(new_target).insert(IsTargeted);
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));
}
}
else {
commands.entity(new_target).insert(IsTargeted);
ew_sfx.send(audio::PlaySfxEvent(audio::Sfx::Click));
}
}
else {
for entity in &q_target {
commands.entity(entity).remove::<IsTargeted>();
ew_sfx.send(audio::PlaySfxEvent(audio::Sfx::Click));
}
}
break; // Only accept a single event per frame
}
}
fn update_target_selectagon(
) {
}