target ui indicating health too (#17)

This commit is contained in:
extrawurst
2025-03-26 00:41:57 +01:00
committed by GitHub
parent 804fac7958
commit 17406b1f00
6 changed files with 214 additions and 13 deletions

View File

@@ -1,4 +1,9 @@
use crate::{keys::KeySpawn, sounds::PlaySound, tb_entities::EnemySpawn};
use std::{collections::HashMap, usize};
use crate::{
heads_ui::HEAD_COUNT, keys::KeySpawn, player::head_id_to_str, sounds::PlaySound,
tb_entities::EnemySpawn,
};
use bevy::prelude::*;
#[derive(Event, Reflect)]
@@ -7,22 +12,47 @@ pub struct Hit {
}
#[derive(Component, Reflect)]
struct Hp(i32);
pub struct Hitpoints {
max: i32,
current: i32,
}
impl Hitpoints {
fn new(v: i32) -> Self {
Self { max: v, current: v }
}
pub fn health(&self) -> f32 {
self.current as f32 / self.max as f32
}
}
#[derive(Component)]
pub struct NpcHead(pub usize);
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);
// TODO: use game state to initialize only once
fn init(mut commands: Commands, query: Query<(Entity, &EnemySpawn), Without<Hitpoints>>) {
let mut names: HashMap<String, usize> = HashMap::default();
for i in 0..HEAD_COUNT {
names.insert(head_id_to_str(i).to_string(), i);
}
for (e, spawn) in query.iter() {
let id = names[&spawn.head];
commands
.entity(e)
.insert((Hitpoints::new(100), NpcHead(id)))
.observe(on_hit);
}
}
fn on_hit(
trigger: Trigger<Hit>,
mut commands: Commands,
mut query: Query<(&mut Hp, &Transform, &EnemySpawn)>,
mut query: Query<(&mut Hitpoints, &Transform, &EnemySpawn)>,
) {
let Hit { damage } = trigger.event();
@@ -32,11 +62,11 @@ fn on_hit(
commands.trigger(PlaySound::Hit);
hp.0 = hp.0.saturating_sub(*damage as i32);
hp.current = hp.current.saturating_sub(*damage as i32);
info!("npc hp changed: {} [{}]", hp.0, trigger.entity());
info!("npc hp changed: {} [{}]", hp.current, trigger.entity());
if hp.0 <= 0 {
if hp.current <= 0 {
commands.entity(trigger.entity()).despawn_recursive();
if !enemy.key.is_empty() {