Menu
CoddyTech

Three Hearts

Part of the Projects section of Coddy's Godot journey. Lesson 33 of 36.

Touching the guard should cost a heart. The three hearts in the top bar are Heart1, Heart2 and Heart3, children of $HUD/Hearts. The guard is an Area2D, so its body_entered fires when it touches the hero:

func _on_enemy_body_entered(body):
	health -= 1
	$HUD/Hearts.get_child(health).visible = false

get_child(i) gives a node's child by its place, counting from 0. After the first hit health is 2, and get_child(2) is Heart3. The hearts disappear from the right.

body_entered fires once per touch. A hero who stays in the guard's path loses a heart each time it comes back.

challenge icon

Challenge

Medium

Make the guard cost the hero a heart.

  1. In main.gd, add var health = 3 and connect $Enemy.body_entered.
  2. On each touch, lower health by one, then hide $HUD/Hearts.get_child(health).

Press Play and touch the guard: the rightmost heart goes. Then Check.

Try it yourself

extends Node2D

var has_key = false

func _ready():
	$Key.body_entered.connect(_on_key_body_entered)
	$DoorZone.body_entered.connect(_on_door_zone_body_entered)

func _on_key_body_entered(body):
	has_key = true
	$Key.queue_free()
	$HUD/KeyIcon.visible = true

func _on_door_zone_body_entered(body):
	if has_key:
		$Door.queue_free()
		$DoorZone.queue_free()

All lessons in Projects

Practice on your own: Godot playground