Nothing stops it at zero.

The problem
Damage just keeps subtracting.
public void TakeDamage( int amount ){ Health -= amount;} public void Heal( int amount ){ Health += amount;}
A big hit takes Health below 0. A big heal takes it past the max. The bar draws both.
The fix
Pin it between two numbers.
Clamp gives back your value, but never lower than min and never higher than max.
value→Math.Clamp( v, 0, max )→0 to max
The fix in code
Clamp every change.
public void TakeDamage( int amount ){ Health = Math.Clamp( Health - amount, 0, MaxHealth );} public void Heal( int amount ){ Health = Math.Clamp( Health + amount, 0, MaxHealth );}
Overkill stops at 0. Overheal stops at the max.
In your engine
Same idea, three spellings.
| Where | Clamp |
|---|---|
| C# | Math.Clamp( v, 0, max ) |
| Unity | Mathf.Clamp( v, 0, max ) |
| s&box | v.Clamp( 0, max ) |
s&box puts it right on the number, so it reads left to right.
The rule
Every change goes through Clamp.
- Floor
- 0
- Ceiling
- MaxHealth
- Every change
- Math.Clamp( ... )
Clamped to 0? Check for death with Health <= 0.