User Interface - acbarker19/Godot-Action-RPG GitHub Wiki
Add Health UI Element and Script
- In the top menu, select Scene > New Scene
- In the left menu, select User Interface
- Rename the Control node as HealthUI
- Attach a script
- 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
- Open the HealthUI scene
- In the left menu, select Add Child Node (Looks like a plus icon)
- Add a new TextureRect node
- Rename the TextureRect to HeartUIEmpty
- Drag the HeartUIEmpty.png file from the bottom left menu to the Texture section of the right menu
- In the right menu, enable Expand under the Texture to allow all hearts to disappear when at zero
- In the right menu, select Stretch Mode > Tile to repeat the icon
- Repeat steps 2-7 for HeartUIFull
- 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