• 12
• 10
• 10
• 13
• 10

# Health bar

This topic is 3226 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

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.

##### Share on other sites
That's fairly elementary mathematics...
current_bar_height = (current_health / max_health) * max_bar_height;
Assuming all values are floating point.

##### Share on other sites
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?

##### Share on other sites
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.