simple hitpoint mechanic

This commit is contained in:
2025-03-12 23:25:13 +01:00
parent 709c1762bd
commit 8946289ac2
8 changed files with 140 additions and 29 deletions

View File

@@ -0,0 +1,41 @@
use crate::tb_entities::EnemySpawn;
use bevy::prelude::*;
#[derive(Event, Reflect)]
pub struct Hit {
pub damage: u32,
}
// TODO: add actual keys
#[derive(Event, Reflect)]
pub struct KeyCollected;
#[derive(Component, Reflect)]
struct Hp(i32);
pub fn plugin(app: &mut App) {
app.add_systems(Update, init);
}
fn init(mut commands: Commands, query: Query<Entity, (With<EnemySpawn>, Without<Hp>)>) {
for e in query.iter() {
commands.entity(e).insert(Hp(100)).observe(on_hit);
}
}
fn on_hit(trigger: Trigger<Hit>, mut commands: Commands, mut query: Query<&mut Hp>) {
let Hit { damage } = trigger.event();
let Ok(mut hp) = query.get_mut(trigger.entity()) else {
return;
};
hp.0 = hp.0.saturating_sub(*damage as i32);
info!("npc hp changed: {} [{}]", hp.0, trigger.entity());
if hp.0 <= 0 {
commands.entity(trigger.entity()).despawn_recursive();
commands.trigger(KeyCollected);
}
}