Menu
CoddyTech

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 icon

Challenge

Medium

Make every row of spikes send you back.

  1. In _ready(), replace the one connect line with a for loop over the group spikes.
  2. Inside the loop, connect each node's body_entered to _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