SPACE SHOOTER
HEALTHBARS
MAKING A FIXED HEALTHBAR
PLAYER
Drawing The Bar
A healthbar consists of two main elements: the foreground that shows current health and a background that shows maximum health. We'll start by drawing the background.
To do so, we'll need to add a render() method to the Player class if you have not done so already. This will override the default game object's render method.
public void render()
{
super.render();
// Set the position and size of the bar
int bX = width / 3;
int bY = height - 100;
int bW = width / 3;
int bH = 25;
// Draw the health bar background in a dark color
fill(125, 0, 0);
rect(bX, bY, bW, bH);
}
Showing Current Health
To show the current health, we'll simply draw a second rectangle on top of the first one. However, we'll make this one be scaled as a percentage of the player's health. We can get this by dividing curHealth by maxHealth.
public void render()
{
/*** code from above *** /
fill(255, 0, 0);
ellipse(bX, bY, bW * curHealth / maxHealth, bH);
}
A fixed healthbar can appear at any point on the screen. It's most useful for things like the player and bosses.
As your game gets more complicated, you could add more attributes with their own bars. For example:
A secondary recharging shield layer
A special weapon that recharges over time
An experience bar that grows when you defeat units.
In each of these cases, the code is the same - you're just working with different data.
POSITIONAL HEALTHBAR
ANY OBJECT
Overhead Healthbar
For enemies, we can't put the health in a fixed position. Instead, use the code above but instead:
Use the enemy's x and y position for the healthbar's location
Use the enemy's w for the healthbar's width
Pick a small value like "5" for the healthbar's height.
To make sure it goes above the enemy, subtract that value from the y position too
Minimalism
Having a healthbar for every enemy isn't required
You might think it looks too cluttered and just have one for the player and boss.
Another option is to only show healthbars on damaged enemies.
To do so, wrap the healthbar display code in an if statement that checks curHealth.
If you add positional healthbars, you can probably remove the debug code from GameObject that displays the health.