1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
use bevy_app::prelude::*;
use bevy_ecs::prelude::*;
use valence_entity::{EntityAnimation, EntityAnimations};
use valence_protocol::packets::play::HandSwingC2s;
use valence_protocol::Hand;

use crate::event_loop::{EventLoopPreUpdate, PacketEvent};

pub struct HandSwingPlugin;

impl Plugin for HandSwingPlugin {
    fn build(&self, app: &mut App) {
        app.add_event::<HandSwingEvent>()
            .add_systems(EventLoopPreUpdate, handle_hand_swing);
    }
}

#[derive(Event, Copy, Clone, PartialEq, Eq, Debug)]
pub struct HandSwingEvent {
    pub client: Entity,
    pub hand: Hand,
}

fn handle_hand_swing(
    mut packets: EventReader<PacketEvent>,
    mut clients: Query<&mut EntityAnimations>,
    mut events: EventWriter<HandSwingEvent>,
) {
    for packet in packets.read() {
        if let Some(pkt) = packet.decode::<HandSwingC2s>() {
            if let Ok(mut anim) = clients.get_mut(packet.client) {
                anim.trigger(match pkt.hand {
                    Hand::Main => EntityAnimation::SwingMainHand,
                    Hand::Off => EntityAnimation::SwingOffHand,
                });
            }

            events.send(HandSwingEvent {
                client: packet.client,
                hand: pkt.hand,
            });
        }
    }
}