Followers 0

# Calculating healthbar percentage

## 3 posts in this topic

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?

0

##### 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.

1

##### Share on other sites

I got it now, Thank you for the reply.

0

## Create an account

Register a new account