A more impressive way to show health is a health bar. Its not that much harder either.
float max = 10; //Maximum amount of health. Make sure this is a float!
float health = 10; //Current amount of player health. Make sure this is a float!
float barWidth = 200; //The length of the bar. Make sure this is a float!
int x = 0, y = 0; //The x and y of the bar. Would probably be assigned in a constructor instead of here
public void render(Graphics g) {
g.setColor(Color.red); //Color of the background of the bar
g.fillRect(x, y, barWidth, 32); //Drawing of the background
g.setColor(Color.green); //The color of the actual bar that changes
g.fillRect(x, y, (health / max) * barWidth, 32); //This draw the bar. The fancy algorithm in the width area is important. Make sure that health variable and the max variable and the barWidth are floats because you need to have decimals in that equation!
g.setColor(Color.black); //The color outline of the bar
g.fillRect(x, y, barWidth, 32); //The drawing of the outline
g.setColor(Color.black); //Color of the text of the health
g.drawString("Health: " + health + "/" + max, x + 12, y); //The drawing of the text
}
public void update() {
//In this method if you wanted the bar to follow a player you would set x = player.x; and y = player.y;
}
That should be it. Very nice stuff here and works flawlessly. Though if you add something like health packs the bar will go past the boundaries so you might want to do something like this:
if(health >= max) {
//Just draw a full green bar instead of the dynamic bar above
}else{
//Draw the bar dynamically like the code above
Feel free to leave a medal. :point:
;D