Skip to content

Instantly share code, notes, and snippets.

@WolfgangSenff
Created June 27, 2024 15:28
Show Gist options
  • Save WolfgangSenff/5979cf05dc92f4b004ba194ffe0b5ed2 to your computer and use it in GitHub Desktop.
Save WolfgangSenff/5979cf05dc92f4b004ba194ffe0b5ed2 to your computer and use it in GitHub Desktop.

Revisions

  1. WolfgangSenff created this gist Jun 27, 2024.
    18 changes: 18 additions & 0 deletions Enemy.gd
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,18 @@
    extends CharacterBody2D
    class_name Enemy

    @export var MoveSpeed : float

    var player : Player

    func _ready() -> void:
    Events.player_ready.connect(_on_player_ready)

    func _on_player_ready(player_node : Player) -> void:
    player = player_node

    func _physics_process(delta : float) -> void:
    if player != null:
    velocity = MoveSpeed * (player.global_position - global_position).normalized() # Simplest behavior: go straight at the player

    move_and_slide()
    5 changes: 5 additions & 0 deletions Events.gd
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,5 @@
    extends Node # Singleton script, no scene required, although you can use them for organization if you wish, just make sure you set the singleton to be the scene and not the script only

    signal player_ready(player_node)

    # That's all there is to this script so far! You can add more here if you have signals that apply to multiple possible other nodes and don't know when/if another node will ever even be added to the scene!
    7 changes: 7 additions & 0 deletions Player.gd
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,7 @@
    extends CharacterBody2D
    class_name Player

    func _ready() -> void:
    ... # Do all the readying you need, and make sure to include other things here

    Events.player_ready.emit(self) # And that's literally it. Because Events is a singleton, any game-object will necessarily be able to rely on it existing and so they know the signal exists. This is called delegating, or rather is one of the many definitions of delegating in programming. You're "delegating" the responsibility of holding the signal to some other node so that the nodes listening to/emitting that signal do not have to have the signal themselves.