Jump to content
  • Advertisement
Sign in to follow this  
Mybowlcut

Health bar

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

If you intended to correct an error in the post then please contact us.

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 this post


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

Share this post


Link to post
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 this post


Link to post
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.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!