Game Development Stack Exchange is a question and answer site for professional and independent game developers. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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


    @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
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


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.