Getting zero with division of two integers?

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

Recommended Posts

I am trying to get health bars working correctly based on a ratio of the character's health to his maximum health. At first it works fine when his health is full, the bar is at it's full length. As soon as he has lost some health, the bar goes to zero even though the health value is not at zero. This is what I'm doing, copied directly from my code:

IN MAIN GAME CLASS:
spriteBatch.Draw(healthBar, new Rectangle((int)bottomGUIPosition.X + 520, (int)bottomGUIPosition.Y + 25, (int)(character.healthRatio * 200), (int)healthBar.Height), Color.White); spriteBatch.Draw(healthBarOutline, new Rectangle((int)bottomGUIPosition.X + 520, (int)bottomGUIPosition.Y + 25, 200, (int)healthBar.Height), Color.White);

IN CHARACTER OBJECT CLASS:
healthRatio = health / maxHealth;

The variable healthRatio is a float, so I have no idea what the problem is. When the health is 145 and the maxHealth is 150, healthRatio should be set to .966667, but instead it goes to zero.
The value is being updated in the character object every frame.
I realize the code isn't very clean right now as too many things are hard coded in, but its just a prototype I started an hour or so ago, so please excuse the mess. Many thanks to whoever can enlighten me as to the cause of this issue.

Share on other sites
Are the "health" and "maxHealth" variables declared as integers? If so, you are using integer division (that returns an integer).

Share on other sites
Just clarifying what Nik02 said, the data type that the result is being stored in doesn't matter here; what's important is the data types of the variables being operated on. With "health / maxHealth", if both are integers, it will generate an integer result, which just happens to then be stored in a float. But the damage has already been done - because the division was done using integers, you're getting a result of 0.

What you want is something like:healthRatio = (float) health / maxHealth;

Share on other sites
O ok, thanks guys, that was the problem. I assumed that because I was storing the result as a float that it wouldn't give me an integer result.

• Game Developer Survey

We are looking for qualified game developers to participate in a 10-minute online survey. Qualified participants will be offered a \$15 incentive for your time and insights. Click here to start!

• 18
• 13
• 9
• 9
• 25
×

Important Information

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!