• Advertisement
Sign in to follow this  

Calculating healthbar percentage

This topic is 1336 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

Hi,

   I am trying to draw a health bar when player get hit by enemy. The healthbar is a rect, like -

rect( x, y, w, h)

The width is 177 and height is 12. The maximum health of the player may bigger then 100. So when player get hit the width of the rect should decrease according to the damage. Since the width of the rect is not 100, I am having a little difficulties to calculate the actual healthbar parcent.

What I am doing is -

unsigned int health = (currentHealth / maxHealth) * 100;

This only works if the width is 100. If I multiply with 177 (actual width of the rect), it always returns 0.
So how do I increase/decrease the percentage of the healthbar according to the width of the rect?

 

Thanks in advance.

Share this post


Link to post
Share on other sites
Advertisement

If currentHealth is less than maxHeath, then that will always evaluate to zero, since (currentHealth / maxHealth) will be zero. If you change your order of operations though, then you can circumvent the "problems" with integer division.

 

Instead of

 

unsigned int health = (currentHealth / maxHealth) * 100;  // ((50 / 150) * 100) --> (0 * 100)   --> 0

 

use

 

unsigned int health = currentHealth * 100 / maxHealth;   // (50 * 100 / 150) -->  (5000 / 150) -->  33

Share this post


Link to post
Share on other sites

Your currentHealth and maxHealth variables are integers, meaning that the result of currentHealth / maxHealth will also be an integer, which means the result of that operation will either be either 0 or 1. Integers are always rounded down, so you'll end up with 0 if currentHealth < maxHealth. You can go two ways here, cast the numbers to floating point numbers and cast back to an integer in the end, or simply multiply by 177 before you divide.

Share this post


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

  • Advertisement