How do you code Health bars?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Chumwadsprite

I’ve been having trouble on how to code health bars. I just don’t know how to make them register damage, make them heal or even just change it’s value!

:bust_in_silhouette: Reply From: kidscancode

For a health bar you can use ProgressBar (plain bar) or TextureProgress (uses a texture to draw the bar).

Setting the bar’s length is done with the value property as in:

$Bar.value = 50

You can also give the bar a max/min value if you want to change the range from the default of 0 through 100. These properties are all documented in the Range class, which both bar types inherit from.

So in your game whenever the character takes damage or heals, update the healthbar by changing its value.

:bust_in_silhouette: Reply From: Xrayez

Suppose you have a node like this that represents a character (this is actually what I’m working on right now, literally):

extends Node2D

signal damaged(by)
signal killed()

const HP_MAX = 100.0
var hp = HP_MAX

func take_damage(impact):
    impact = clamp(impact, 0.0, 1.0)
    var damage = HP_MAX * impact
    var prev_hp = hp
    hp -= damage
    hp = clamp(hp, 0, HP_MAX)

    if prev_hp != hp:
	    emit_signal("damaged", damage)

    if hp <= 0.0:
	    emit_signal("killed")

This character holds and manages health on it’s own. Then you create your GUI elements that just listens to defined signals like damaged:

extends ProgressBar

onready var character = get_node() # get it somewhere

func _ready():
    character.connect("damaged", self, "_on_character_damage_taken")

 func _on_character_damage_taken(impact):
    # Update health bar according to character's current HP
    value = character.hp
    # do something else ...

Tested just now and it works quite alright for me (though I have a bit different implementation).