Health bar

Started by
3 comments, last by Mybowlcut 14 years, 11 months ago
Hey. I'm trying to create a health bar that is just a rectangle that grows in height as the player gains health. Google didn't help much so I'm just curious what the formula is to calculate the height of the bar from the players health. E.g. if the player had 5 health points left out of 10 possible points and the bar is a certain size, how would I scale the top of it down (or calculate where the top would be) to represent the health left. Cheers.

Advertisement
That's fairly elementary mathematics...
current_bar_height = (current_health / max_health) * max_bar_height;
Assuming all values are floating point.
Heya,

Luckily it's pretty easy, here's how!

First you get what percent of their health they have:

Percent = Health / MaxHealth;

which would give you 0.5 if they had 5 out of 10 health

Next, you multiply that by how big your health bar is

HealthHeight = Percent * HealthBarHeight;

if you had a health bar that was 30 pixels (or units) high, you'd get 30*0.5 or 15 units high.

Make sense?
Your first step is to calculate the percentage of health the player has, and let's call that percentage "X":

X = (current health / maximum health) * 100

Then, how you want to display that percentage is up to you, but here's my favorite way (because it's easiest). Have your health bar be 100 pixels wide and however many pixels high (let's say 20 for this example). First, have your application draw a red rectangle for the total size of the health bar: from (0,0) to (100, 20) for example. Then, draw a green bar over it, starting from (0,0) and extending to (X, 20).

So, if the player has 100% health, the green bar completely overlaps the red bar. If the player has 50% health, the green bar overlaps the left half of the red bar. If the player has 0% health, the green bar doesn't overlap the red bar at all, and only a red bar is visible.

That's all there is to it. And if you want your health bar to be of a different width, all you need to do is scale a few values.
Website (with downloads of my games)
Blog (updates on current projects)
Seeds of Time Online has returned!
Codeka, I know it's fairly elementary but I'm not that great with maths...

Cheers for all your replies!

This topic is closed to new replies.

Advertisement