Take the 2-minute tour ×
Game Development Stack Exchange is a question and answer site for professional and independent game developers. It's 100% free, no registration required.

Im making 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(?)
share|improve this question

1 Answer 1

up vote 6 down vote accepted

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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