Skip to main content

azalea_client/plugins/
attack.rs

1use azalea_core::{game_type::GameMode, tick::GameTick};
2use azalea_entity::{
3    Attributes, Physics, indexing::EntityIdIndex, metadata::Sprinting, update_bounding_box,
4};
5use azalea_physics::PhysicsSystems;
6use azalea_protocol::packets::game::ServerboundAttack;
7use bevy_app::{App, Plugin, Update};
8use bevy_ecs::prelude::*;
9use derive_more::{Deref, DerefMut};
10use tracing::warn;
11
12use super::packet::game::SendGamePacketEvent;
13use crate::{interact::SwingArmEvent, movement::MoveEventsSystems, respawn::perform_respawn};
14
15pub struct AttackPlugin;
16impl Plugin for AttackPlugin {
17    fn build(&self, app: &mut App) {
18        app.add_message::<AttackEvent>()
19            .add_systems(
20                Update,
21                handle_attack_event
22                    .before(update_bounding_box)
23                    .before(MoveEventsSystems)
24                    .after(perform_respawn),
25            )
26            .add_systems(
27                GameTick,
28                (
29                    increment_ticks_since_last_attack,
30                    update_attack_strength_scale.after(PhysicsSystems),
31                    // in vanilla, handle_attack_queued is part of `handleKeybinds`
32                    handle_attack_queued
33                        .before(super::movement::update_pose)
34                        .before(super::tick_end::game_tick_packet),
35                )
36                    .chain(),
37            );
38    }
39}
40
41/// A component that indicates that this client will be attacking the given
42/// entity next tick.
43#[derive(Clone, Component, Debug)]
44pub struct AttackQueued {
45    pub target: Entity,
46}
47#[allow(clippy::type_complexity)]
48pub fn handle_attack_queued(
49    mut commands: Commands,
50    mut query: Query<(
51        Entity,
52        &mut TicksSinceLastAttack,
53        &mut Physics,
54        &mut Sprinting,
55        &AttackQueued,
56        &GameMode,
57        &EntityIdIndex,
58    )>,
59) {
60    for (
61        client_entity,
62        mut ticks_since_last_attack,
63        mut physics,
64        mut sprinting,
65        attack_queued,
66        &game_mode,
67        entity_id_index,
68    ) in &mut query
69    {
70        let target_entity = attack_queued.target;
71        let Some(target_entity_id) = entity_id_index.get_by_ecs_entity(target_entity) else {
72            warn!("tried to attack entity {target_entity} which isn't in our EntityIdIndex");
73            continue;
74        };
75
76        commands.entity(client_entity).remove::<AttackQueued>();
77
78        commands.trigger(SendGamePacketEvent::new(
79            client_entity,
80            ServerboundAttack {
81                entity_id: target_entity_id,
82            },
83        ));
84        commands.trigger(SwingArmEvent {
85            entity: client_entity,
86        });
87
88        // we can't attack if we're in spectator mode but it still sends the attack
89        // packet
90        if game_mode == GameMode::Spectator {
91            continue;
92        };
93
94        ticks_since_last_attack.0 = 0;
95
96        physics.velocity = physics.velocity.multiply(0.6, 1.0, 0.6);
97        **sprinting = false;
98    }
99}
100
101/// Queues up an attack packet for next tick by inserting the [`AttackQueued`]
102/// component to our client.
103#[derive(Message)]
104pub struct AttackEvent {
105    /// Our client entity that will send the packets to attack.
106    pub entity: Entity,
107    /// The entity that will be attacked.
108    pub target: Entity,
109}
110pub fn handle_attack_event(mut events: MessageReader<AttackEvent>, mut commands: Commands) {
111    for event in events.read() {
112        commands.entity(event.entity).insert(AttackQueued {
113            target: event.target,
114        });
115    }
116}
117
118#[derive(Bundle, Default)]
119pub struct AttackBundle {
120    pub ticks_since_last_attack: TicksSinceLastAttack,
121    pub attack_strength_scale: AttackStrengthScale,
122}
123
124#[derive(Clone, Component, Default, Deref, DerefMut)]
125pub struct TicksSinceLastAttack(pub u32);
126pub fn increment_ticks_since_last_attack(mut query: Query<&mut TicksSinceLastAttack>) {
127    for mut ticks_since_last_attack in query.iter_mut() {
128        **ticks_since_last_attack += 1;
129    }
130}
131
132#[derive(Clone, Component, Default, Deref, DerefMut)]
133pub struct AttackStrengthScale(pub f32);
134pub fn update_attack_strength_scale(
135    mut query: Query<(&TicksSinceLastAttack, &Attributes, &mut AttackStrengthScale)>,
136) {
137    for (ticks_since_last_attack, attributes, mut attack_strength_scale) in query.iter_mut() {
138        // look 0.5 ticks into the future because that's what vanilla does
139        **attack_strength_scale =
140            get_attack_strength_scale(ticks_since_last_attack.0, attributes, 0.5);
141    }
142}
143
144/// Returns how long it takes for the attack cooldown to reset (in ticks).
145pub fn get_attack_strength_delay(attributes: &Attributes) -> f32 {
146    ((1. / attributes.attack_speed.calculate()) * 20.) as f32
147}
148
149pub fn get_attack_strength_scale(
150    ticks_since_last_attack: u32,
151    attributes: &Attributes,
152    in_ticks: f32,
153) -> f32 {
154    let attack_strength_delay = get_attack_strength_delay(attributes);
155    let attack_strength = (ticks_since_last_attack as f32 + in_ticks) / attack_strength_delay;
156    attack_strength.clamp(0., 1.)
157}