coreheart/crates/combat/src/lib.rs

127 lines
3 KiB
Rust
Raw Normal View History

2025-08-24 19:45:33 -04:00
//bevy system signatures often violate these rules
#![allow(clippy::type_complexity)]
#![allow(clippy::too_many_arguments)]
2025-08-24 20:13:22 -04:00
use bevy::prelude::*;
2025-08-24 19:45:33 -04:00
pub struct CombatPlugin;
impl Plugin for CombatPlugin {
fn build(&self, app: &mut App) {
app.add_observer(on_attack).add_observer(on_die);
}
}
2025-08-25 08:31:33 -04:00
#[derive(Component, Clone, Debug, PartialEq, Eq)]
pub enum Team {
Core,
Immune,
}
2025-08-24 19:45:33 -04:00
#[derive(Event, Debug)]
pub struct Attacked {
pub attacker: Option<Entity>,
pub amount: f32,
}
#[derive(Event, Debug)]
pub struct Died {
pub slayer: Option<Entity>,
}
#[derive(Component, Clone, Debug)]
pub struct Health {
pub max: f32,
pub current: f32,
}
impl Health {
pub fn new(health: f32) -> Self {
Self {
max: health,
current: health,
}
}
}
impl Default for Health {
fn default() -> Self {
Self {
max: 1.0,
current: 1.0,
}
}
}
#[derive(Component, Clone, Debug, Default)]
#[require(Health)]
pub struct Defense {
pub amount: f32,
}
impl Defense {
pub fn calc_damage(&self, incoming_damage: f32) -> f32 {
2025-08-24 20:13:22 -04:00
let min_damage = 0.1;
if incoming_damage < min_damage {
return 0.;
}
(incoming_damage - self.amount * 0.5).max(min_damage)
2025-08-24 19:45:33 -04:00
}
pub fn new(amount: f32) -> Self {
Self { amount }
}
}
fn on_attack(
trigger: Trigger<Attacked>,
mut commands: Commands,
2025-08-25 08:31:33 -04:00
attacker_query: Query<&Team>,
mut attacked_query: Query<(&mut Health, Option<&Defense>, Option<&Team>)>,
2025-08-24 19:45:33 -04:00
names: Query<&Name>,
) {
2025-08-25 08:31:33 -04:00
let Ok((mut health, opt_defense, opt_team)) = attacked_query.get_mut(trigger.target()) else {
2025-08-24 19:45:33 -04:00
warn!("tried to attack entity without health");
return;
};
2025-08-25 08:31:33 -04:00
if let Some(Ok(attacker_team)) = trigger.event().attacker.map(|a| attacker_query.get(a))
&& let Some(team) = opt_team
&& team == attacker_team
{
info!("avoiding friendly fire!");
return;
}
2025-08-24 19:45:33 -04:00
let defense = opt_defense.cloned().unwrap_or_default();
let damage_taken = defense.calc_damage(trigger.event().amount);
health.current = (health.current - damage_taken).max(0.0);
info!(
"{:?} attacked {:?} for {} damage. New health = {}",
trigger
.event()
.attacker
.map(|e| names.get(e).ok())
.flatten(),
names.get(trigger.target()),
damage_taken,
health.current
);
if health.current <= 0.
&& let Ok(mut ec) = commands.get_entity(trigger.target())
{
ec.trigger(Died {
slayer: trigger.event().attacker,
});
}
}
fn on_die(trigger: Trigger<Died>, names: Query<&Name>, mut commands: Commands) {
if let Ok(mut ec) = commands.get_entity(trigger.target()) {
info!(
"{:?} killed {:?}!",
trigger.event().slayer.map(|e| names.get(e).ok()).flatten(),
names.get(trigger.target())
);
ec.despawn();
}
}