simple hitpoint mechanic
This commit is contained in:
41
src/npc.rs
41
src/npc.rs
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user