Giving Entities Hit Points
Hands-on Rust — by Herbert Wolverson (65 / 120)
👈 Chapter 8 Health and Melee Combat | TOC | Adding a Heads-up Display 👉
Adding hit points to entities requires a new component type. This is a common theme in ECS design patterns — whenever you want to represent something new about entities, you add a component type. Open src/components.rs and add another component type to the file:
HealthSimpleMelee/health/src/components.rs
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Health {
pub current: i32,
pub max: i32
}
This component stores both the current and max (maximum) hit points of an entity. It’s important to store the maximum hit points because health bars are scaled to show how much health an entity is missing. When an entity is healed, you can use the maximum hit points to ensure it’s not healed above its maximum.
Now that you have a Health component, let’s add it to the player.
Adding Health to the Player
Open src/spawner.rs and locate the spawn_player function. Extend it to include a health component for the player:
HealthSimpleMelee/health/src/spawner.rs
ecs.push(
(Player,
pos,
Render{
color: ColorPair::new(WHITE, BLACK),
glyph : to_cp437('@')
},
» Health{ current…