How to Program a Health Bar

Health bars are a popular way of representing a character's health. They can be displayed above of enemies, players, and even some destructible objects. In this tutorial I will provide you the math and pseudo-code necessary to program a basic health bar.

Health bar proportional size

Given the following variables:

a = Maximum life (HP value)

b = Life bar maximum width (in pixels)

c = Current life (HP value)

d = Life bar width (in pixels)

We know when current life c equals maximum Life a, the life bar width d should be equals to life bar maximum width b.

Therefore, we can represent these properties using the proportion formula:

We want to know the value of d when current life c varies, therefore we isolate d :

We have the condition that it is impossible to divide by zero:

We can represent this formula in programming code, just like this:

if(a!=0) d = (b*c)/a;

Better yet, as a matter of making the code readable:

if(maxLife!=0) lifeBarWidth = (lifeBarMaxWidth*life)/maxLife;

Now we are ready to draw our Health Bar in the correct size.

Colours based on the percentage of current health

It's also common to paint the bar in different colours so the player can spot faster how much life the character has.

We can use the proportion formula to know the percentage

percentage = (100*life)/maxlife;

and then paint the health bar

//if life <= 30% paint red

if(percentage<=30)

lifebar.graphics.beginFill("#F000").drawRect(5, 5, lifeBarWidth,20);

//if life <= 60% paint yellow

else if(percentage<=60)

lifebar.graphics.beginFill("#FF00").drawRect(5, 5, lifeBarWidth,20);

//if life > 60% paint green

else

lifebar.graphics.beginFill("#0F00").drawRect(5, 5, lifeBarWidth,20);

Colours proportional to current health

A really cool effect is when the colour of the life bar changes proportionally to the current amount of health. To achieve that, we need to calculate the values of the colours GREEN and RED. Blue is always 0.

//proportion - green

green = Math.round( (255*percentage)/50 );

if(green>255) green = 255;

//proportion - red

red = Math.round( (255*(percentage-50))/50 );

if(red>255) red = 255;

red = Math.abs(red-255);

//draw health bar (blue = 0 and alpha 255)

lifebar.graphics.beginFill(red,green,0,255)).drawRect(5, 5, lifeBarWidth,20);