1
\$\begingroup\$

I'm making a health bar for my game that looks like this:

public void healthBar(Canvas canvas)
{
    float healthScale = happy.getHP() / happy.getMaxHP();
    Rect rect = new Rect(20, 20,(120 * (int)healthScale), 40);
    Paint paint = new Paint();
    paint.setColor(Color.RED);
    canvas.drawRect(20, 20, 220 * healthScale, 40, paint);
}

This is called every time my game renders. When the game starts it's where I want it, but as soon as my character ("happy") takes any damage, it dissapears. And I know that his hp only gets subtracted by 5 every time he gets hit. So this should not happen?

Example:

@Startup: happy.getHP() == 100, happy.getMaxHP == 100. 
when damaged HP -=5, -> happy.getHP() == 95 -> healthscale == 0,95 -> 220 * 0,95 == new width for Rect(?)
\$\endgroup\$
8
\$\begingroup\$

I have a good feeling that getHP() and getMaxHP() are returning integral values (int, short, long, byte, etc). If so, they should be cast to floating point numbers (float or double) before dividing otherwise integer division will take place, causing the health scale to be either 1 or 0 and nothing in between. This also goes for this: 120 * (int)healthScale. If you truncate a floating point number: 0.95, you'll lose everything after the decimal place, resulting in 0.

As a side note: It's worth using a debugger to narrow down errors like this one. If you don't have a debugger, find one. If you can't find one, use the poor man's debugger: use printouts.

\$\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.