-
Notifications
You must be signed in to change notification settings - Fork 0
Design Patterns
Mex777 edited this page Jun 4, 2024
·
1 revision
Singletons are objects that ensure there's only one instance of a particular class throughout the entire game. They provide global access to their data and functionality. In Godot, you can implement singletons using auto-loaded nodes. Here are some examples:
-
Player Singleton:
- Manages player-related data such as health points (HP) and skin customization.
- Auto-loaded node:
res://Player.gd
- Access it globally with Player.method()
-
Game Singleton:
- Handles in-game currency (coins), current level, god mode, and cutscene state.
- Auto-loaded node:
res://Game.gd
- Access it globally with Game.method()
-
Save Singleton:
- Responsible for saving and loading game progress.
- Auto-loaded node:
res://Save.gd
- Access it globally with Save.method()
The observer pattern facilitates loosely coupled communication between objects. In Godot, we achieve this using signals. Here's an example:
-
Stun Ability and Enemies:
- When Aurora uses the stun ability, emit a signal (e.g.,
"stun_activated"
). - All enemies within her range (that have a
handle_stun
function) connect to this signal. - No need for manual checks; the signal automatically notifies relevant enemies.
- When Aurora uses the stun ability, emit a signal (e.g.,
-
Enemies attacking:
- When a character enters their range, enemies receive a signal based on that signal they check if the character is the player and they start attacking
# Start chasing the player when it enters chaser's range
func _on_chase_range_body_entered(body: CharacterBody2D) -> void:
if body.name == "Aurora":
player = body
Game.enter_combat()
chasing = true
# Stop chasing the player when it leaves chaser's range
func _on_chase_range_body_exited(body: CharacterBody2D) -> void:
if body.name == "Aurora":
chasing = false
Game.exit_combat()
player = null