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

2 Answers 2

1
\$\begingroup\$

The width of the red rectangle should be:

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

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .