Many Spikes, One Function
Part of the Signals and Collisions section of Coddy's Godot journey. Lesson 21 of 27.
A level can have many spikes that all do the same thing. Connect them all to one function with a loop over their group:
for spike in get_tree().get_nodes_in_group("spikes"):
spike.body_entered.connect(_on_spike_body_entered)Each turn of the loop connects the next spike's body_entered. Whichever row you touch, the same function runs and gets your body.
A fifth row added to the group works with no new code. The four rows here are in the group spikes.
Challenge
MediumMake every row of spikes send you back.
- In
_ready(), replace the oneconnectline with aforloop over the groupspikes. - Inside the loop, connect each node's
body_enteredto_on_spike_body_entered.
Press Play and walk into any spikes: you are back at the start. Then Check.
Try it yourself
extends Node2D
func _ready():
$Spikes1.body_entered.connect(_on_spike_body_entered)
func _on_spike_body_entered(body):
body.position = Vector2(80, 280)
All lessons in Signals and Collisions
Practice on your own: Godot playground