Call a function based on percentage of health (int)

Hello all!

I am wondering what the best way to run a function based on health percentage.
Example: If enemy is below 70% health, do a cool mechanic.

I have designed the mechanic on my mega boss character, but the way I trigger the mechanic (function) is kind of awful in my eyes. This is how I do it:

//function is updated each time the enemy takes damage
public void DamageEnemy(float damage){ 

 currentHealth -= damage; //HP goes down as the enemy takes damage
 
 if(isMegaBoss){ //check if enemy is a mega boss
     if(currentHealth / health <= 0.9f && currentHealth / health >= 0.85f)
                 SendInReinforcement();
     else if(currentHealth / health <= 0.7f && currentHealth / health >= 0.65f)
                 SendInReinforcement();
     else if(currentHealth / health <= 0.5f && currentHealth / health >= 0.45f)
                 SendInReinforcement();
 } 
}

So as you see, I want to trigger this mechanic each time the boss reaches 90%, 70%, 50% of his health.
But there has to be a better way to check this? I’m bad at math, that’s probably my problem :smiley:

In advance, thanks for the help!

Cheers,
Simon

What is the health variable? maybe use another variable for knowing what reinforcements you’ve already send?

private int sentReinforcements = 0;
if(isMegaBoss){
      if(currentHealth / health <= 0.9f && sentReinforcements == 0)
                  SendInReinforcement();
                  sentReinforcements ++;
      else if(currentHealth / health <= 0.7f && sentReinforcements == 1) 
                  SendInReinforcement();
                  sentReinforcements ++;
      else if(currentHealth / health <= 0.5f && sentReinforcements == 2)
                  SendInReinforcement();
                  sentReinforcements ++;
  } 

other then that i can’t think of anything else to clean your code up. (and it’ll fix if he sends out reinforcements twice while inbetween 0.9 and 0.85 health for example)

Well. If you want to check for 2 options in the if statement the way you wrote it looks good to me…

you can just make one variable in the DamageEnemy function called (For example) healthAfterDamage and then do

healthAfterDamage = currentHealth / health;

Then check that variable. This way you will divide only once…

Additionally you can do all of the if’s in one statement, but it will be kinda long…

if (healthAfterDamage <= 0.9f && healthAfterDamage >= 0.85f || currentHealth / health <= 0.7f && currentHealth / health >= 0.65f || and so on).