All lessons
Lesson 10

Health and Damage

Lose health by touching a hazard. Mixes a signal with a direct function call, and shows when to use each.

Loading the game engine. This takes a moment the first time.

Build style

This file has no code at all. Everything happens in the other three, and they talk using signals plus one direct function call.

HOW A HIT TRAVELS

  1. The player walks into a hazard.
  2. hazard.gd calls body.take_damage(1) right on the player. It can do that because body_entered already handed it the player.
  3. player.gd lowers "health", then emits health_changed.
  4. hud.gd connects to health_changed and redraws the number.

The scenes

UI node · 2D node · % unique name · .tscn instanced scene

health_and_damage.tscn
  • HealthAndDamage Node2D health_and_damage.gd
  • HealthPlayer CharacterBody2D player.tscn
  • Hazard1 Area2D hazard.tscn
  • Hazard2 Area2D hazard.tscn
  • Hazard3 Area2D hazard.tscn
  • Hazard4 Area2D hazard.tscn
  • HUD CanvasLayer hud.tscn
hazard.tscn
  • Hazard Area2D hazard.gd
  • ColorRect
  • CollisionShape2D
hud.tscn
  • HUD CanvasLayer hud.gd
  • MarginContainer
  • HealthLabel Label %
  • HomeButton Button %
player.tscn
  • HealthPlayer CharacterBody2D player.gd
  • Sprite2D
  • CollisionShape2D
Build style
extends Node2D