DEV Community

Cover image for Godot HUD tutorial 2D: hearts, a stamina bar that holds a grudge, and icons that gray out when locked
Darrell Best
Darrell Best

Posted on

Godot HUD tutorial 2D: hearts, a stamina bar that holds a grudge, and icons that gray out when locked

A Godot 4.3 run of the finished HUD: hearts drop, a sprint drains the stamina bar while a pale ghost bar lags behind, the fireball slot goes muted with a clockwise cooldown sweep and countdown, the last heart pulses, and a locked ice shard slot sits at the end

A label that says "HP: 1 / 5" is technically a HUD. So is a sticky note on your monitor. Both work. Neither one makes a player sweat.

This is a step by step Godot HUD tutorial for 2D: a row of hearts driven by HP, a stamina bar with a "ghost" drain that holds a grudge for a moment so the hit reads, a pulse on the last heart, and a skill bar where the fireball goes muted during its cooldown, sweeps back to color, and counts down. One slot stays locked, because every RPG needs a thing you can see and not have.

The HUD never touches the player. The player emits signals. The HUD listens. Everything in the GIF above is a real Godot 4.3 run, recorded with Movie Maker, and every script below is the file that ran.

Left: the same demo with a plain Label and default ProgressBar. Right: hearts, ghost stamina bar, cooldown sweep and a locked slot, fed by the same player

1. Set up the project

I used Godot 4.3 with the Compatibility renderer and a 1280x720 viewport. That is the setup everything below was tested on.

Copy in only the icons you need. This demo uses three state folders from Cozy RPG HUD Icons:

res://icons/normal/01_heart.png
res://icons/normal/02_heart_empty.png
res://icons/normal/04_stamina.png
res://icons/normal/14_sword.png
res://icons/normal/20_fireball.png
res://icons/muted/14_sword.png
res://icons/muted/20_fireball.png
res://icons/locked/21_ice_shard.png
Enter fullscreen mode Exit fullscreen mode

The icons are smooth vector-style art at 128x128, so leave texture filtering on (the pack README says the same). They get scaled down to 40, 56 and 104 px here, and filtering keeps the outlines smooth.

The muted and locked files have the same names as the normal ones. That matters later: a state change is a folder change. (An earlier devlog walks through all six states. Here we just put three of them to work.)

2. The player only emits signals

The player owns the numbers. It has no idea a HUD exists. Save this as res://player.gd:

extends Node
# player.gd: owns the numbers. It never touches the HUD. It only emits signals.

signal health_changed(current: int, max_hp: int)
signal stamina_changed(current: float, max_stamina: float)
signal skill_used(skill_id: StringName, cooldown: float)

const SKILLS := {&"sword": 0.8, &"fireball": 3.0}

@export var max_hp := 5
@export var max_stamina := 100.0
@export var sprint_cost := 40.0     # per second
@export var stamina_regen := 30.0   # per second
@export var regen_delay := 0.6      # seconds after the last spend

var hp := max_hp
var stamina := max_stamina
var sprinting := false
var _regen_wait := 0.0
var _cooldowns := {}  # skill_id -> seconds left


func take_hit(amount: int) -> void:
    hp = clampi(hp - amount, 0, max_hp)
    health_changed.emit(hp, max_hp)


func heal(amount: int) -> void:
    hp = clampi(hp + amount, 0, max_hp)
    health_changed.emit(hp, max_hp)


func spend_stamina(amount: float) -> bool:
    if stamina < amount:
        return false
    stamina -= amount
    _regen_wait = regen_delay
    stamina_changed.emit(stamina, max_stamina)
    return true


func try_cast(skill_id: StringName) -> bool:
    if _cooldowns.get(skill_id, 0.0) > 0.0:
        return false
    _cooldowns[skill_id] = SKILLS[skill_id]
    skill_used.emit(skill_id, SKILLS[skill_id])
    return true


func _process(delta: float) -> void:
    for id in _cooldowns.keys():
        _cooldowns[id] = maxf(_cooldowns[id] - delta, 0.0)

    var old := stamina
    if sprinting and stamina > 0.0:
        stamina = maxf(stamina - sprint_cost * delta, 0.0)
        _regen_wait = regen_delay
        if stamina == 0.0:
            sprinting = false
    elif _regen_wait > 0.0:
        _regen_wait -= delta
    else:
        stamina = minf(stamina + stamina_regen * delta, max_stamina)
    if stamina != old:
        stamina_changed.emit(stamina, max_stamina)
Enter fullscreen mode Exit fullscreen mode

Three signals carry everything the HUD needs: health_changed, stamina_changed and skill_used. The player also refuses a cast while that skill is still cooling down, so the HUD never has to be the one that says no.

The regen_delay is small but important. Without it, stamina starts refilling the frame you stop spending, and the ghost bar in step 5 never gets its moment.

3. Build the HUD scene

Make a new scene, res://hud.tscn, with this tree:

HUD (CanvasLayer)                  hud.gd
  Top (PanelContainer)             top-left, offset 24, 24
    VBox (VBoxContainer)
      %Hearts (HBoxContainer)      heart_row.gd
      StaminaRow (HBoxContainer)
        StaminaIcon (TextureRect)  04_stamina.png, 40x40
        %StaminaBar (Control)      stamina_bar.gd, min size 260x26
          Ghost (ProgressBar)      Full Rect
          Bar (ProgressBar)        Full Rect
  Skills (PanelContainer)          anchored bottom center
    Row (HBoxContainer)
      %Sword (skill_slot.tscn)     icon_file = 14_sword.png
      %Fireball (skill_slot.tscn)  icon_file = 20_fireball.png
      %IceShard (skill_slot.tscn)  icon_file = 21_ice_shard.png, locked = on
Enter fullscreen mode Exit fullscreen mode

The % means Access as Unique Name (right click the node). Then scripts can say %Hearts and you can rearrange the tree without fixing paths.

Styling is plain StyleBoxFlat overrides:

  • Both panels: dark cocoa background, a 3 px brown border, 16 px corner radius.
  • Ghost: a dark background style and a pale cream fill.
  • Bar: a green fill and a StyleBoxEmpty background, so the ghost shows through behind it.
  • Turn off Show Percentage on both bars. Nobody in a boss fight wants to read "70%".

Order matters. Bar comes after Ghost in the tree, so it draws on top.

4. A heart row with a low-health pulse

One TextureRect per heart. Full or empty. Save as res://heart_row.gd:

extends HBoxContainer
# heart_row.gd: one TextureRect per heart. Full or empty. Pulses on the last heart.

const FULL := preload("res://icons/normal/01_heart.png")
const EMPTY := preload("res://icons/normal/02_heart_empty.png")

@export var heart_size := 56
@export var low_hp := 1

var _pulse: Tween


func set_hearts(current: int, max_hp: int) -> void:
    while get_child_count() < max_hp:
        var rect := TextureRect.new()
        rect.expand_mode = TextureRect.EXPAND_IGNORE_SIZE
        rect.stretch_mode = TextureRect.STRETCH_KEEP_ASPECT_CENTERED
        rect.custom_minimum_size = Vector2(heart_size, heart_size)
        rect.pivot_offset = rect.custom_minimum_size / 2
        add_child(rect)
    for i in get_child_count():
        var rect: TextureRect = get_child(i)
        rect.visible = i < max_hp
        rect.texture = FULL if i < current else EMPTY
    _set_pulse(current > 0 and current <= low_hp, current - 1)


func _set_pulse(on: bool, index: int) -> void:
    if _pulse:
        _pulse.kill()
        _pulse = null
    for rect in get_children():
        rect.scale = Vector2.ONE
        rect.modulate = Color.WHITE
    if not on:
        return
    var heart: TextureRect = get_child(index)
    _pulse = create_tween().set_loops()
    _pulse.set_trans(Tween.TRANS_SINE)
    _pulse.tween_property(heart, "scale", Vector2(1.2, 1.2), 0.25)
    _pulse.parallel().tween_property(heart, "modulate", Color(1.35, 0.85, 0.85), 0.25)
    _pulse.tween_property(heart, "scale", Vector2.ONE, 0.35)
    _pulse.parallel().tween_property(heart, "modulate", Color.WHITE, 0.35)
Enter fullscreen mode Exit fullscreen mode

The row builds its own hearts the first time set_hearts runs, so max_hp can change without editing the scene.

The pulse is a looping Tween on the last full heart: scale up a little, tint it warmer, then come back. Two details worth knowing:

  • Set pivot_offset to the center. The default pivot is the top left corner, and a heart that pulses from its corner looks like it is trying to leave.
  • Kill the old Tween before you make a new one. An infinite loop you forgot about will keep pulsing a heart you already healed.

5. A stamina bar with a ghost drain

The trick is two ProgressBars stacked on top of each other. The front one drops at once. The ghost behind it waits, then drains. The pale gap between them is the damage, and it stays on screen long enough to read. The ghost holds a grudge, but only for 0.35 seconds.

Save as res://stamina_bar.gd:

extends Control
# stamina_bar.gd: the front bar drops at once. A ghost bar behind it waits, then drains.

@export var ghost_delay := 0.35
@export var ghost_time := 0.45

@onready var bar: ProgressBar = get_node("Bar")
@onready var ghost: ProgressBar = get_node("Ghost")

var _ghost_tween: Tween


func set_value(current: float, max_value: float) -> void:
    bar.max_value = max_value
    ghost.max_value = max_value
    if current >= bar.value:
        # Refill: no ghost needed. Only lift the ghost if the bar passed it.
        bar.value = current
        ghost.value = maxf(ghost.value, current)
        return
    # A drop: park the ghost where the bar was, then let it catch up later.
    ghost.value = maxf(ghost.value, bar.value)
    bar.value = current
    if _ghost_tween:
        _ghost_tween.kill()
    _ghost_tween = create_tween()
    _ghost_tween.tween_interval(ghost_delay)
    _ghost_tween.tween_property(ghost, "value", current, ghost_time) \
        .set_trans(Tween.TRANS_QUAD).set_ease(Tween.EASE_OUT)
Enter fullscreen mode Exit fullscreen mode

Each drop restarts the ghost Tween. During a sprint, stamina_changed fires every frame, so the ghost keeps getting told to wait. It stays parked at the starting value until you stop running, then drains in one smooth slide. That is the "how much did that sprint cost me" moment, and it took zero extra code.

Refills skip the ghost. Nobody needs a dramatic reveal of stamina coming back.

If you have bar art, TextureProgressBar works the same way. Both are Range nodes, so value and max_value behave the same. Change the two type hints in the script. (I only ran the ProgressBar version for this post.)

6. A skill slot that goes muted on cooldown

A TextureProgressBar already has everything a cooldown needs: a texture under, a texture on top, and a radial fill mode. Put the muted icon under and the normal icon on top, set the fill to clockwise, and value becomes "how recharged is this".

Make res://skill_slot.tscn with a TextureProgressBar root (custom minimum size 104x104, Nine Patch Stretch on) and one child Label called Countdown set to Full Rect, centered, size 34, with a dark outline. Attach res://skill_slot.gd:

extends TextureProgressBar
# skill_slot.gd: color icon when ready. Muted icon plus a clockwise sweep while cooling down.

@export var icon_file := "20_fireball.png"
@export var locked := false

@onready var countdown: Label = get_node("Countdown")

var cooling := false


func _ready() -> void:
    fill_mode = FILL_CLOCKWISE
    min_value = 0.0
    max_value = 1.0
    step = 0.0
    countdown.text = ""
    if locked:
        texture_under = load("res://icons/locked/" + icon_file)
        texture_progress = null
        value = 0.0
    else:
        texture_under = load("res://icons/muted/" + icon_file)
        texture_progress = load("res://icons/normal/" + icon_file)
        tint_under = Color(0.7, 0.7, 0.7)  # darken the muted part so the sweep reads
        value = 1.0


func start_cooldown(seconds: float) -> void:
    if locked or cooling:
        return
    cooling = true
    value = 0.0
    var tween := create_tween()
    tween.tween_method(_tick.bind(seconds), 0.0, 1.0, seconds)
    await tween.finished
    cooling = false
    countdown.text = ""
    # A quick flash so "ready" is noticed
    modulate = Color(1.6, 1.6, 1.6)
    create_tween().tween_property(self, "modulate", Color.WHITE, 0.25)


func _tick(t: float, seconds: float) -> void:
    value = t
    countdown.text = "%.1f" % (seconds * (1.0 - t))
Enter fullscreen mode Exit fullscreen mode

What happens on a cast:

  1. value jumps to 0, so the whole slot shows the muted icon.
  2. tween_method runs _tick from 0 to 1 over the cooldown. The color icon sweeps back in clockwise and the label counts down.
  3. When the Tween finishes, the label clears and the slot flashes once so the player notices it is ready.

tint_under darkens the muted part a little. Muted is designed to keep some color, which is nice in a menu and a bit too polite for a cooldown sweep. The darker under texture makes the edge of the sweep easy to see at a glance.

The locked slot uses the locked icon as its under texture, has no progress texture, and ignores start_cooldown. It just sits there with its little padlock, being aspirational.

With Nine Patch Stretch on, the 128 px icons drew at the 104 px slot size in this 4.3 run, clockwise fill included.

7. Wire the HUD to the player

res://hud.gd connects the signals and pulls the starting values once:

extends CanvasLayer
# hud.gd: listens to a player. It knows nothing about damage, sprinting or spells.

@onready var hearts: HBoxContainer = %Hearts
@onready var stamina_bar: Control = %StaminaBar
@onready var slots := {
    &"sword": %Sword,
    &"fireball": %Fireball,
}


func watch(player: Node) -> void:
    player.health_changed.connect(hearts.set_hearts)
    player.stamina_changed.connect(stamina_bar.set_value)
    player.skill_used.connect(_on_skill_used)
    # Pull the starting values once, so the HUD is right on frame one.
    hearts.set_hearts(player.hp, player.max_hp)
    stamina_bar.set_value(player.stamina, player.max_stamina)


func _on_skill_used(skill_id: StringName, cooldown: float) -> void:
    if slots.has(skill_id):
        slots[skill_id].start_cooldown(cooldown)
Enter fullscreen mode Exit fullscreen mode

From whatever scene owns both, it is three lines. This is from the demo's main.gd:

var hud = load("res://hud.tscn").instantiate()
add_child(hud)
hud.watch(player)
Enter fullscreen mode Exit fullscreen mode

The HUD never asks the player for anything after that. You can delete the HUD and the player keeps working. You can test the HUD with a fake player that only emits signals. You can swap the hearts for a bar next month and nobody else has to know.

For the demo I drove the player from a script: one hit, a 1.2 second sprint, a sword swing, a fireball, two more hits, a 30 stamina dodge, a recast attempt while the fireball was still cooling down, then a heal. The calls are the public ones above, for example:

player.spend_stamina(30.0)
Enter fullscreen mode Exit fullscreen mode

The finished HUD mid fight: one pulsing heart, a ghost segment on the stamina bar after a dodge, the fireball muted with 1.3 seconds left, and the locked ice shard slot

What I checked

All of this ran in Godot 4.3.stable (Compatibility renderer, xvfb, Movie Maker at 30 FPS). Both runs exited with code 0 and no script errors.

  • The HUD found 2 cooldown slots (sword, fireball) and built 5 hearts on frame one.
  • Signals in order: health_changed(4, 5), skill_used(sword, 0.8), skill_used(fireball, 3), health_changed(2, 5), health_changed(1, 5), health_changed(3, 5).
  • Stamina after the 1.2 second sprint: 52 of 100. In the frames, the ghost stayed at the pre-sprint value until the sprint stopped, then drained.
  • A second fireball cast during its cooldown returned false, and the slot kept counting down.
  • The last heart pulsed at 1 HP and stopped when healed to 3.
  • The locked slot never changed.
  • Run length: 330 frames, 11 seconds. The GIF and both stills come from those runs.

Tuning notes

  • Ghost timing: 0.3 to 0.4 seconds of delay reads well. Much longer and players think the bar is broken.
  • Low HP threshold: low_hp is an export. With 10 hearts you probably want it at 2 or 3.
  • Countdown format: %.1f is good for short cooldowns. For anything over 10 seconds, whole numbers look calmer.
  • Keyboard hints, tooltips and a "not enough stamina" shake are easy to add on top. Each one is another listener, not another reference to the player.

Skip the icon homework

The code here is short. The slow part of a HUD like this is the art: a full and an empty heart that match, plus a muted and a locked version of every skill, all lined up so a swap is just a path change.

That is what Cozy RPG HUD Icons is. You get 64 icon designs in six states (normal, muted, grayscale, locked, muted locked, grayscale locked), all as 128x128 PNGs, plus six matching 1024x1024 atlases with JSON coordinates for each state. Same file names in every state folder, same atlas cells in every sheet. The hearts, stamina, sword, fireball and ice shard above are five of the 64.

A watermarked sample of five icons from the pack in the normal, muted and locked states

Get them here: Cozy RPG HUD Icons

Questions: cozy-hud-icons@darrellbest.com

Top comments (0)