2
\$\begingroup\$

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

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);
\$\endgroup\$
  • \$\begingroup\$ What type of variable is "g"? Can you show how you initiate it? Pls \$\endgroup\$ – Adi Andrei Jun 19 '17 at 15:11
1
\$\begingroup\$

The width of the red rectangle should be:

enemyWidth * (enemyCurrentHealth / enemyMaxHealth);
\$\endgroup\$
  • \$\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
0
\$\begingroup\$

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.

\$\endgroup\$

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.