User Interface - acbarker19/Godot-Action-RPG GitHub Wiki

Add Health UI Element and Script

  1. In the top menu, select Scene > New Scene
  2. In the left menu, select User Interface
  3. Rename the Control node as HealthUI
  4. Attach a script
  5. Add the following code to set the amount of hearts and observe the player health:
var hearts = 4 setget set_hearts
var max_hearts = 4 setget set_max_hearts

func set_hearts(value):
	hearts = clamp(value, 0, max_hearts)
	
func set_max_hearts(value):
	max_hearts = max(value, 1)
	self.hearts = min(hearts, max_hearts)   // if hearts is greater than max_hearts, hearts is lowered
	
func _ready():
	self.max_hearts = PlayerStats.max_health
	self.hearts = PlayerStats.health
	PlayerStats.connect("health_changed", self, "set_hearts")
	PlayerStats.connect("max_health_changed", self, "set_max_hearts")

Display the Health as Heart Icons

  1. Open the HealthUI scene
  2. In the left menu, select Add Child Node (Looks like a plus icon)
  3. Add a new TextureRect node
  4. Rename the TextureRect to HeartUIEmpty
  5. Drag the HeartUIEmpty.png file from the bottom left menu to the Texture section of the right menu
  6. In the right menu, enable Expand under the Texture to allow all hearts to disappear when at zero
  7. In the right menu, select Stretch Mode > Tile to repeat the icon
  8. Repeat steps 2-7 for HeartUIFull
  9. In the HealthUI script, add the following the show the correct number of hearts:
onready var heartUIFull = $HeartUIFull
onready var heartUIEmpty = $HeartUIEmpty

func set_hearts(value):
	hearts = clamp(value, 0, max_hearts)
	if heartUIFull != null:
		heartUIFull.rect_size.x = hearts * 15   // 15 is the number of pixels wide the full heart icon is

func set_max_hearts(value):
	max_hearts = max(value, 1)
	self.hearts = min(hearts, max_hearts)
	if heartUIEmpty != null:
		heartUIEmpty.rect_size.x = max_hearts * 15   // 15 is the number of pixels wide the empty heart icon is