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

Only Spikes1 sends you back. In _ready(), connect the body_entered of every node in the group spikes to _on_spike_body_entered.

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)
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Signals and Collisions

Practice on your own: Godot playground