• Create Account

## Calculating healthbar percentage

Old topic!

Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

3 replies to this topic

### #1HeExists  Members

273
Like
0Likes
Like

Posted 29 May 2014 - 12:30 PM

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?

### #2phil_t  Members

7648
Like
3Likes
Like

Posted 29 May 2014 - 12:39 PM

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.

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

### #3Mussi  GDNet+

3998
Like
1Likes
Like

Posted 29 May 2014 - 12:40 PM

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.

### #4HeExists  Members

273
Like
0Likes
Like

Posted 29 May 2014 - 12:48 PM

I got it now, Thank you for the reply.

Old topic!

Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.