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.

enter image description here


    g.fillRect(enemy.getX(), enemy.getY(), enemy.getWidth(), 5);
    g.fillRect(enemy.getX(), enemy.getY(), enemy.getHealth() * 4, 5);
  • \$\begingroup\$ What type of variable is "g"? Can you show how you initiate it? Pls \$\endgroup\$ – Adi Andrei Jun 19 '17 at 15:11

The width of the red rectangle should be:

enemyWidth * (enemyCurrentHealth / enemyMaxHealth);
| improve this answer | |
  • \$\begingroup\$ great thanks. I only problem that fillRect only takes int. is there way I can work around it? \$\endgroup\$ – user1924249 Oct 25 '15 at 21:23
  • \$\begingroup\$ 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. \$\endgroup\$ – KevLoughrey Oct 25 '15 at 21:31
  • \$\begingroup\$ i found the issue. the algorthim is this: (enemyWidth * enemyCurrentHealth) / enemyMaxHealth; \$\endgroup\$ – 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()

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);


| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.