# how to set up health bar rect that depends on health?

I need some help with game math.

What I am using:

I am using java awt library.

What I am trying to do:

I am trying to build enemy health bar, which will display as an rectangle. I am display two rectangles. First one is black rectange and it will act as in base container. 2nd one is red rectangle and it will act as helath bar.

now the max size of enemy health bar will be enemy.getWidth(). I need some help with 2nd red rectangle width. how can I set up so that it dependents on enemy.getHealth() and max is enemy.getWidth.?

and enemy.getHealth() will be 4.

Code:

    g.setColor(Color.black);
g.fillRect(enemy.getX(), enemy.getY(), enemy.getWidth(), 5);
g.setColor(Color.red);
g.fillRect(enemy.getX(), enemy.getY(), enemy.getHealth() * 4, 5);

• What type of variable is "g"? Can you show how you initiate it? Pls – Adi Andrei Jun 19 '17 at 15:11

The width of the red rectangle should be:

enemyWidth * (enemyCurrentHealth / enemyMaxHealth);

• great thanks. I only problem that fillRect only takes int. is there way I can work around it? – user1924249 Oct 25 '15 at 21:23
• You can cast a float value to an int. You have to do it like this in Java: int myInt = (int)(Math.round(floatValue)); Source. – KevLoughrey Oct 25 '15 at 21:31
• i found the issue. the algorthim is this: (enemyWidth * enemyCurrentHealth) / enemyMaxHealth; – user1924249 Oct 25 '15 at 21:51

It's simple the percentage of current health compared to max health. Something like

percentage =enemy.getHealth()/enemy.getWidth()
fillRect.Width(fillRect.Width()*percentage);


To change the color, you can have something like

if (percentage<=0.25)  gsetColor(Color.red);
if (percentage>0.25 && percentage<0.5)  gsetColor(Color.yellow);


etc.