In Lesson 5, we added jumping, a tilemap stage, and a camera that follows the player. But touching a coin still does nothing. In this lesson, we'll use signals to build the "rules of the game": touch a coin and it disappears and your score goes up; touch an enemy and you're sent back to the start.
Finished project for Lesson 6: project-lesson06.zip (12 KB)
What is a signal?
A signal is how a node announces "hey, this just happened." A button announces "I was pressed," a timer announces "time's up," and the Area2D we use in this lesson announces "something entered me."
Whoever wants to hear the announcement connects one of its functions to the signal. Then, whenever the signal fires, that function is called automatically.
The player touches a coin
→ The coin (Area2D) emits the body_entered signal
→ The connected _on_body_entered() is called
→ The coin disappearsYou could skip signals and check in code every frame, "am I overlapping the player?" But then the checking side needs to know about the player, and every time you add coins or enemies the code gets more tangled. With signals, the sender just says "it happened," and the receiver just says "when it happens, do this." Neither needs to know how the other works inside.
For more on using signals, see The complete guide to signals in Godot 4.
Turn the coin into an Area2D
Right now the coin is a Sprite2D, just a picture, so it can't tell when it's touched. We'll change it to an Area2D. As the table in Lesson 4 said, an Area2D is a region that "doesn't collide, but tells you when something overlaps it." We don't want the player to stop on top of a coin, so this is exactly right for coins.
- Open
coin.tscn, right-click the rootCoin→ Change Type..., chooseArea2D, and click Change. - An Area2D can't display an image, so the Texture setting goes away. Add a
Sprite2Das a child ofCoinand set its Texture tocoin.svg. - Add a
CollisionShape2Das a child ofCoin, set its Shape to "New CircleShape2D," and set Radius to20. - Select
Coinand, under Collision in the Inspector, set Layer to only 3 (coin) and Mask to only 2 (player). This means "watch for the player only." - Open the Groups tab in the dock on the right, click "+" (Add a new group), enter
coinsas the name, and click OK. Ifcoinsis checked, this coin is a member of thecoinsgroup (we'll use this to count the score).
Coin (Area2D) … group: coins
├─ Sprite2D
└─ CollisionShape2D
Connect a signal in the editor
Next, change line 1 of coin.gd to extends Area2D and save (the root's type changed, so leaving it as is causes an error). Then we'll hook up the "something entered" signal.
- In
coin.tscn, selectCoinand open the Signals tab in the dock on the right. It lists the signals that node can emit. - Double-click
body_entered(body: Node2D)under theArea2Dheading (or select it and click Connect... at the bottom). - The Connect a Signal to a Method dialog opens. Check that the target is
Coinand that Receiver Method: is_on_body_entered, then click Connect. - An
_on_body_enteredfunction is added to the script editor automatically. A green arrow icon on its left means it's connected.
Fill in the function body to finish coin.gd like this:
extends Area2D
# Signal emitted when the coin is collected (a custom signal we made)
signal collected
# How far (in pixels) and how fast the coin bobs
@export var float_height: float = 8.0
@export var float_speed: float = 3.0
var time: float = 0.0
var start_y: float = 0.0
func _ready() -> void:
start_y = position.y
func _process(delta: float) -> void:
time += delta
# sin() glides smoothly between -1 and 1, which makes the coin bob up and down
position.y = start_y + sin(time * float_speed) * float_height
# Called when the player touches the coin (connected in the editor's "Signals" tab)
func _on_body_entered(_body: Node2D) -> void:
collected.emit()
queue_free()body_enteredis the signal emitted when a physics body enters the area. The body that entered is passed in as thebodyargument. Since we set Mask to 2 (player), only the player triggers it.- The
_in front of the argument name marks it as "not used." The auto-generated function names itbody, but Godot shows a yellow warning for unused arguments, so we renamed it_body. queue_free()means "please delete this node." It's removed safely once the current frame's processing is done.signal collectedandcollected.emit()are a custom signal, which we'll explain next.
A signal you connect in the editor is recorded as a single line at the end of the scene file coin.tscn:
[connection signal="body_entered" from="." to="." method="_on_body_entered"]Because we changed the coin scene, all six coins placed in main.tscn are now Area2Ds. Run with F5 and check that coins disappear when you touch them.
Count the score with your own signal
Next up is the score. When a coin disappears, we want to tell the rest of the game "I got collected." This is where we make our own signal.
signal collected
...
collected.emit()You declare a signal with signal name and emit it with name.emit(). The coin just shouts "I got collected"; it doesn't know who owns the score or where it's displayed. That's the beauty of signals.
Set up the score display
We want the score to stay in the same spot on screen even when the camera moves, so we put the label inside a CanvasLayer. Children of a CanvasLayer aren't affected by the camera (we'll cover this in more detail next lesson).
- Add a
CanvasLayeras a child ofMaininmain.tscnand name itHUD. - Add a
Labelas a child ofHUDand name itScoreLabel. Set Text toCoins: 0, Layout → Transform → Position to840,24, Size to280,48, Horizontal Alignment to Right, and Theme Overrides → Font Sizes → Font Size to32.
Connect a signal in code
Right-click Main → "Attach Script" to create res://main.gd, and write the following:
extends Node2D
# Number of coins collected
var score: int = 0
# The label that shows the score. With @onready, it gets filled in right before _ready
@onready var score_label: Label = $HUD/ScoreLabel
func _ready() -> void:
# In code, connect the collected signal of every node in the "coins" group (that is, every coin)
for coin: Node in get_tree().get_nodes_in_group("coins"):
coin.connect("collected", _on_coin_collected)
update_score_label()
# Called when any coin emits its collected signal
func _on_coin_collected() -> void:
score += 1
update_score_label()
func update_score_label() -> void:
score_label.text = "Coins: " + str(score)get_tree().get_nodes_in_group("coins")gathers every node in thecoinsgroup. No matter how many coins you add, you won't need to change this code.coin.connect("collected", _on_coin_collected)is connecting a signal in code. It does in one line the same thing you did in the editor's "Signals" tab.- A variable marked
@onreadygets its value right after the node is ready.$HUD/ScoreLabelmeans "my child HUD's child, ScoreLabel."
The result is the same either way. For connections that stay within a scene (the coin receiving its own body_entered), connecting in the editor has the advantage that you can see what's connected to what in the "Signals" tab. Connecting in code is handy for things whose number grows later, like here, or for connecting nodes you create while the game is running all at once.
Make an enemy that walks around
Finally, let's make an enemy that walks back and forth across the stage. The enemy doesn't need to block the player either; it just needs to know when it's touched. So, like the coin, it's an Area2D.
For the enemy art, use the one drawn for this series. Download it and add it to your project.
Enemy image: enemy.svg (56 × 48 pixels)
- Use Scene → New Scene to create an
Area2Droot and name itEnemy. - Add child nodes
Sprite2D(Texture:enemy.svg) andCollisionShape2D(New RectangleShape2D, Size44,36, Position0,4). - Under
Enemy's Collision, set Layer to only 4 (enemy) and Mask to only 2 (player). - Save it as
res://enemy.tscnand attach the following script,res://enemy.gd, toEnemy.
extends Area2D
# Walking speed (pixels per second) and how far to walk left and right from the starting position
@export var speed: float = 120.0
@export var patrol_distance: float = 160.0
var start_x: float = 0.0
# 1.0 moves right, -1.0 moves left
var direction: float = 1.0
func _ready() -> void:
start_x = position.x
# Signals can be connected in code too (same as connecting them in the editor)
body_entered.connect(_on_body_entered)
func _process(delta: float) -> void:
position.x += direction * speed * delta
# If we get too far from the starting position, turn around
if position.x > start_x + patrol_distance:
direction = -1.0
elif position.x < start_x - patrol_distance:
direction = 1.0
# Flip the image horizontally to face the direction we're moving
$Sprite2D.flip_h = direction < 0.0
# Called when something touches the enemy
func _on_body_entered(body: Node2D) -> void:
# If whatever touched us has respawn() (that is, it's the player), send it back to the start
if body.has_method("respawn"):
body.respawn()- The movement works much like the coin from Lesson 3. We remember the starting position
start_x, and when it gets more thanpatrol_distanceaway, we flipdirection. body_entered.connect(_on_body_entered)is the same kind of connection we made in the editor for the coin, but done in code. It means the same as writingconnect("body_entered", ...), but this way Godot catches a misspelled signal name before the game even runs.- We toggle
$Sprite2D.flip_hso the enemy faces the way it's walking.
Go back to main.tscn and use "Instantiate Child Scene..." to place two enemy.tscn instances. In the finished project, the first Enemy is on the ground at (1400, 488), the second, Enemy2, is on a high platform at (1952, 232), and Enemy2's Patrol Distance is set to 64 in the Inspector so it doesn't walk off the platform.
Send the player back to the start on enemy contact
The enemy's _on_body_entered calls respawn() on whatever touched it, if that thing has such a function. Let's add that function to the player. Here's the whole player.gd:
extends CharacterBody2D
# Left/right movement speed (pixels per second)
@export var speed: float = 300.0
# Gravity strength: the downward speed increases by this much every second
@export var gravity: float = 1200.0
# Speed at the moment of the jump. Up on screen is negative, so this is a negative value
@export var jump_velocity: float = -600.0
# Starting position (we come back here after touching an enemy)
var start_position: Vector2 = Vector2.ZERO
func _ready() -> void:
start_position = position
# Called on every physics step (60 times per second by default)
func _physics_process(delta: float) -> void:
# When not standing on the floor, increase the downward speed a little at a time (this is gravity)
if not is_on_floor():
velocity.y += gravity * delta
# The moment the jump button is pressed, jump if we're on the floor
if Input.is_action_just_pressed("jump") and is_on_floor():
velocity.y = jump_velocity
# If the button is released while still rising, halve the upward speed (short hop)
if Input.is_action_just_released("jump") and velocity.y < 0.0:
velocity.y *= 0.5
# -1 for left, 1 for right, 0 if neither is pressed
var direction: float = Input.get_axis("move_left", "move_right")
velocity.x = direction * speed
# Move according to velocity. If we hit a floor or wall, stop there
move_and_slide()
# Send the player back to the start. Called by the enemy (enemy.gd)
func respawn() -> void:
position = start_position
velocity = Vector2.ZERO- In
_ready, we remember where the player was first placed instart_position. respawn()moves it back there and sets the velocity to 0. If we didn't reset the velocity, the player would restart still carrying its falling momentum.- The enemy checks "does this thing have respawn?" with
body.has_method("respawn")before calling it. The enemy doesn't need to know the details of the player; it just asks it to "go back."
And that's it. The finished main.tscn tree looks like this:
Main (Node2D) … main.gd
├─ Title (Label)
├─ TileMapLayer
├─ Player (player.tscn)
├─ Coin – Coin6 (coin.tscn)
├─ Enemy (enemy.tscn)
├─ Enemy2 (enemy.tscn)
└─ HUD (CanvasLayer)
└─ ScoreLabel (Label)
Run with F5. Collecting coins increases the number in the top right, and touching an enemy sends you back to the start. The coin on the high platform is guarded by an enemy, so time your jump.
- Add one more enemy and set its Speed to
240. It suddenly gets a lot harder. - Make it print
print("Cleared!")when all the coins are collected. Hint: inside_on_coin_collected, check whetherscoreequals the number of coins. - Guess what happens if you delete the
collected.emit()line incoin.gd, then try it.
Common pitfalls
| Symptom | Cause and fix |
|---|---|
| Coins don't disappear when touched | One of these: (1) 2 isn't turned on in Coin's Mask, (2) the player's Layer isn't 2 (Lesson 5), or (3) the signal isn't connected. In the "Signals" tab, check that _on_body_entered appears under body_entered. |
Running the game shows Script inherits from native type 'Sprite2D', so it can't be assigned to an object of type 'Area2D'. | You changed the root's type, but line 1 of coin.gd still says extends Sprite2D. Change it to extends Area2D. |
| Coins disappear but the score doesn't go up | The coins aren't in the coins group, or main.gd isn't attached to Main. Also check the group name's spelling ("coins"). |
Running the game shows Node not found: "HUD/ScoreLabel" and Invalid assignment of property or key 'text' with value of type 'String' on a base object of type 'null instance'. | The names or parent-child structure in $HUD/ScoreLabel don't match the Scene dock. Check the node names (including upper/lower case) and that ScoreLabel is a child of HUD. |
| Touching an enemy doesn't send you back to the start | Check that 2 is turned on in Enemy's Mask, and that the function in player.gd is named respawn, the same as in the enemy's code. If the name doesn't match, has_method quietly returns false, so there's no error. |
Working with AI
Signals are about relationships: "which signal, on which node, goes to which function." So when you ask AI for help, the trick is to spell out those relationships clearly.
- A (chat): it's good at explaining how signals work and at writing the code. You make the connections in the editor yourself. The AI can't tell from your code that "the signal isn't connected," so when you describe a problem, also tell it what the "Signals" tab shows.
- B (Claude Code, etc.): it can write both
.gdand.tscnfiles, so it can even make connections by adding a[connection ...]line. But it can't see whether the coin actually disappears when the player touches it. You'll go back and forth, telling it what happened when you ran the game. - C (+ MCP): with Godot MCP Pro, the AI can connect signals inside the editor (
connect_signal), set groups (set_node_groups), and check the list of connections (find_signal_connections). You can also leave it to check things like whether a signal actually fired while the game was running (watch_signals), or to move the player and read the score label (simulate_action,get_game_node_properties).
Whichever approach you use, play it yourself at the end to check. Enemy speed and coin placement make a big difference to how fun the game is, and that's your call.
Recap and what's next
- A signal announces "something happened." The receiving side connects a function to it
Area2D'sbody_enteredtells you when something touches it. Mask decides what to watch for- You can connect signals in the editor's "Signals" tab or with
connect()in code - Make your own signal with
signal nameand emit it withname.emit() - Groups let you handle nodes of the same kind all together
queue_free()deletes a node
Now it's a game you can actually play. Next time: UI and screen transitions. We'll make a title screen, a game over screen, and a clear screen, and use an Autoload to remember the score across screens.
Want AI to handle connecting signals and testing them?
With Godot MCP Pro, Claude Code or Cursor can connect signals inside the editor, run the game, and even confirm that a signal actually fired (190 tools, $15 one-time purchase). You can finish this series without MCP.
Learn more about Godot MCP Pro · The complete guide to signals in Godot 4