Like in most games with healthbars, the units in my game have a hp_bar object which is a frame, with a slightly smaller rectangle inside which should get smaller (and change color) as a unit loses hp, but I'm unsure how to work the math which will make the rectangle size an integer which represents an percentage rather than the actual hp.

Say the hp bar is 40 pixels in width, and hp is some arbitrary integer amount, what is the python magic to convert the hp to hp bar width?


1 Answer 1


Well, consider the following:

The ratio between the max width of the bar and the real width of the bar is the same as the ratio between max HP and HP; so:

width / max_width = hp / max_hp =>

width = hp / max_hp * max_width
  • \$\begingroup\$ ie (hp/max_hp) is % hp. %hp * max_width gives width in pixels that hp bar should be. \$\endgroup\$
    – bobobobo
    Commented Apr 27, 2013 at 15:22

You must log in to answer this question.

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