Created
March 14, 2025 14:01
-
-
Save viniciusemferreira/28b8c6aff0befbaa0e939b556e432e21 to your computer and use it in GitHub Desktop.
The HealthComponent script for Godot 4 is a simple and reusable health system for game entities. It tracks an entity’s health, allowing it to take damage and emit signals when health changes, decreases, or is depleted. The script also provides a function to get the current health as a percentage. When health reaches zero, a death event is trigge…
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extends Node | |
class_name HealthComponent | |
## Signal emitted when health changes. Sends the amount of change. | |
signal health_changed(amount: float) | |
## Signal emitted specifically when health decreases. Sends the amount of damage taken. | |
signal health_decreased(amount: float) | |
## Signal emitted when health reaches zero. | |
signal health_depleted | |
## The maximum health value for this component. | |
@export var max_health: float | |
## The current health value of the entity. | |
var health: float | |
# Initializes the health to the maximum value when the node is ready. | |
func _ready() -> void: | |
health = max_health | |
## Reduces health by a given amount and emits relevant signals. | |
## If health reaches zero, it triggers the `died()` function. | |
func damage(amount: float) -> void: | |
health = max(health - amount, 0) | |
health_decreased.emit(amount) | |
health_changed.emit(amount) | |
if health <= 0: | |
died.call_deferred() | |
## Returns the current health as a percentage of the max health. | |
func get_percentage_health() -> float: | |
return min(health / max_health, 1) | |
## Handles the death event by emitting the `health_depleted` signal. | |
func died() -> void: | |
health_depleted.emit() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment