coreheart/crates/combat/src/lib.rs

248 lines
6.1 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-31 19:00:19 -04:00
pub mod projectiles;
2025-08-26 08:16:40 -04:00
use std::time::Duration;
use avian3d::prelude::*;
2025-08-24 20:13:22 -04:00
use bevy::prelude::*;
use physics::PhysicsLayers;
use resources::{Drops, Resources};
2025-08-26 08:16:40 -04:00
use state::GameSystemSet;
2025-08-24 19:45:33 -04:00
pub struct CombatPlugin;
impl Plugin for CombatPlugin {
fn build(&self, app: &mut App) {
2025-08-31 19:00:19 -04:00
app.add_plugins(projectiles::ProjectilePlugin)
.add_observer(on_attack)
2025-08-26 08:16:40 -04:00
.add_observer(on_die)
.add_systems(
FixedUpdate,
tick_invulnerability.in_set(GameSystemSet::StatusEffects),
)
.register_type::<Team>();
2025-08-24 19:45:33 -04:00
}
}
#[derive(Default, Component, Clone, Copy, Debug, PartialEq, Eq, Reflect)]
2025-08-25 08:31:33 -04:00
pub enum Team {
#[default]
Core = 1,
Inhabitant = 2,
}
impl Team {
pub fn collision_layers(&self) -> CollisionLayers {
match self {
Team::Core => CollisionLayers::new(PhysicsLayers::Core, LayerMask::ALL),
Team::Inhabitant => CollisionLayers::new(PhysicsLayers::Inhabitant, LayerMask::ALL),
}
}
2025-08-31 19:00:19 -04:00
pub fn enemy_layers(&self) -> LayerMask {
match self {
Team::Core => PhysicsLayers::Inhabitant.into(),
Team::Inhabitant => PhysicsLayers::Core.into(),
2025-08-31 19:00:19 -04:00
}
}
2025-08-25 08:31:33 -04:00
}
2025-08-26 08:16:40 -04:00
#[derive(Event, Debug, Default)]
2025-08-24 19:45:33 -04:00
pub struct Attacked {
pub attacker: Option<Entity>,
pub amount: f32,
2025-08-26 08:16:40 -04:00
pub skip_invulnerability: bool,
2025-08-24 19:45:33 -04:00
}
#[derive(Event, Debug)]
pub struct GaveDamage {
pub target: Entity,
pub amount: f32,
pub skip_invulnerability: bool,
}
2025-08-24 19:45:33 -04:00
#[derive(Event, Debug)]
pub struct Died {
pub slayer: Option<Entity>,
}
#[derive(Component, Clone, Debug)]
2025-08-26 08:16:40 -04:00
#[require(InvulnerabilityTime)]
2025-08-24 19:45:33 -04:00
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,
}
}
}
2025-08-26 08:16:40 -04:00
#[derive(Component, Clone, Debug)]
pub struct InvulnerabilityTime {
pub duration: Duration,
}
impl Default for InvulnerabilityTime {
fn default() -> Self {
Self {
duration: Duration::from_secs_f32(0.25),
}
}
}
#[derive(Component, Clone, Debug)]
pub struct Invulnerable {
pub time_remaining: Option<Timer>,
}
impl From<&InvulnerabilityTime> for Invulnerable {
fn from(value: &InvulnerabilityTime) -> Self {
Self {
time_remaining: Some(Timer::new(value.duration, TimerMode::Once)),
}
}
}
2025-08-24 19:45:33 -04:00
#[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>,
2025-08-26 08:16:40 -04:00
mut attacked_query: Query<
(
&mut Health,
&InvulnerabilityTime,
Option<&Defense>,
Option<&Team>,
),
Without<Invulnerable>,
>,
2025-08-24 19:45:33 -04:00
names: Query<&Name>,
) {
2025-08-26 08:16:40 -04:00
let Ok((mut health, invulnerability, opt_defense, opt_team)) =
attacked_query.get_mut(trigger.target())
else {
2025-08-24 19:45:33 -04:00
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
{
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);
let old_health = health.current;
health.current = (old_health - damage_taken).max(0.0);
2025-08-24 19:45:33 -04:00
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 let Some(attacker) = trigger.event().attacker {
commands.trigger_targets(
GaveDamage {
target: trigger.target(),
amount: old_health - health.current,
skip_invulnerability: trigger.event().skip_invulnerability,
},
attacker,
);
}
2025-08-26 08:16:40 -04:00
if let Ok(mut ec) = commands.get_entity(trigger.target()) {
if health.current <= 0. {
ec.trigger(Died {
slayer: trigger.event().attacker,
});
} else if !trigger.event().skip_invulnerability {
ec.insert(Invulnerable::from(invulnerability));
}
2025-08-24 19:45:33 -04:00
}
}
fn on_die(
trigger: Trigger<Died>,
names: Query<&Name>,
drops: Query<&Drops>,
mut resources: ResMut<Resources>,
mut commands: Commands,
) {
if let Ok(drop) = drops.get(trigger.target()) {
resources.souls += drop.souls;
}
2025-08-24 19:45:33 -04:00
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();
}
}
2025-08-26 08:16:40 -04:00
fn tick_invulnerability(
mut commands: Commands,
mut query: Query<(Entity, &mut Invulnerable)>,
time: Res<Time>,
) {
for (entity, mut invulnerable) in query.iter_mut() {
if let Some(timer) = &mut invulnerable.time_remaining {
timer.tick(time.delta());
if timer.finished() {
match commands.get_entity(entity) {
Ok(mut ec) => {
ec.remove::<Invulnerable>();
}
Err(e) => {
error!(
"could not remove invulnerability from {:?} - {:?}",
entity, e
);
}
}
}
}
}
}