- Home /
Question by
BHS · Jun 09, 2012 at 07:03 AM ·
convertpercentagehealth
Calculating Percentages for an if Statement in JS
Hi,
If there's one thing I'd like to learn more about programming, it'd be the math. It can be extremely helpful for pretty much everything.
What I need to do is convert my players health to a percentage, easy *.01 but how can I use this in an if statement?
Like:
if (playersHealth <= 90%)
{
//do this
}
if (playersHealth <= 80%)
{
//do this
}
I need to do it this way because my player grows levels and as he progresses levels his health increases. This needs to be constant, at 90% of player's health this will always happen, whether the health is 10,000 or 100. Thanks in advance.
Comment
Best Answer
Answer by dood_legacy · Jun 09, 2012 at 08:30 AM
Just keep track of the total starting health, and the current health, and divide the current by the total...
float maxHealth = 100.0f;
float playersHealth = maxHealth;
// somewhere else, health gets decreased
playersHealth -= 30.0f;
// then do your test
if (0.9f >= (playersHealth / maxHealth))
{
//do this
}
if (0.8f >= (playersHealth / maxHealth))
{
//do this
}
Answer by whydoidoit · Jun 09, 2012 at 07:44 AM
You should do something like this:
if((playersHealth/maxHealth) < 0.9) {
//Do something when the health is less than 90%
}