Your Own Signal
Part of the Signals and Collisions section of Coddy's Godot journey. Lesson 7 of 27.
You can give a node your own signals. Declare one at the top of the script with signal:
extends Area2D
signal hitSend it with emit() when the thing happens:
func _on_body_entered(body):
hit.emit()Older code may use emit_signal("hit"). It does the same.
The spikes only report that someone got hit. What a hit does is up to the code that listens. Here the script on Main listens for hit:
extends Node2D
# Main listens for the spikes' hit signal, once the spikes have one.
func _ready():
if $Spikes.has_signal("hit"):
$Spikes.hit.connect(_on_spikes_hit)
func _on_spikes_hit():
print("Ouch!")
$Player.modulate = Color(1, 0.42, 0.42)You will write listeners like this soon. In this lesson you edit only the spikes.
Challenge
EasyGive the spikes a signal and send it when someone steps on them.
- Declare
signal hitat the top ofspikes.gd. - In
_on_body_entered, send it withhit.emit().
Press Play and walk onto the spikes: the Console shows Ouch! and you turn coral. Then Check.
Try it yourself
extends Area2D
func _ready():
body_entered.connect(_on_body_entered)
func _on_body_entered(body):
pass
All lessons in Signals and Collisions
2Signals
Areas Meet AreasYour Own SignalSignals With ValuesAnother Node's SignalListen to Your SignalPractice on your own: Godot playground