Make Games with Godot 4 and AI · Lesson 6 of 11

Godot 4 Signals: Area2D Coins and Enemies (Lesson 6)

Touch a coin and it disappears and your score goes up; touch an enemy and you're sent back to the start. You'll build the rules of the game with signals, using three approaches: connecting in the editor, connecting in code, and making your own signal.

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)

The finished game from Lesson 6. "Coins: 1" appears in the top right, and a purple enemy is on the right side of the ground
Where we'll end up in this lesson. We've just grabbed one coin from the ground, and a purple enemy is walking in from the right

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.

How the signal flows
The player touches a coin
  → The coin (Area2D) emits the body_entered signal
    → The connected _on_body_entered() is called
      → The coin disappears

You 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.

  1. Open coin.tscn, right-click the root Coin → Change Type..., choose Area2D, and click Change.
  2. An Area2D can't display an image, so the Texture setting goes away. Add a Sprite2D as a child of Coin and set its Texture to coin.svg.
  3. Add a CollisionShape2D as a child of Coin, set its Shape to "New CircleShape2D," and set Radius to 20.
  4. Select Coin and, under Collision in the Inspector, set Layer to only 3 (coin) and Mask to only 2 (player). This means "watch for the player only."
  5. Open the Groups tab in the dock on the right, click "+" (Add a new group), enter coins as the name, and click OK. If coins is checked, this coin is a member of the coins group (we'll use this to count the score).
coin.tscn structure
Coin (Area2D)  … group: coins
├─ Sprite2D
└─ CollisionShape2D
coin.tscn open with the root Coin (Area2D) selected. Under Collision in the Inspector, Layer 3 and Mask 2 are turned on
The coin, now an Area2D. Under Collision in the Inspector, Layer is 3 and Mask is 2

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.

  1. In coin.tscn, select Coin and open the Signals tab in the dock on the right. It lists the signals that node can emit.
  2. Double-click body_entered(body: Node2D) under the Area2D heading (or select it and click Connect... at the bottom).
  3. The Connect a Signal to a Method dialog opens. Check that the target is Coin and that Receiver Method: is _on_body_entered, then click Connect.
  4. An _on_body_entered function 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:

coin.gd
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_entered is the signal emitted when a physics body enters the area. The body that entered is passed in as the body argument. 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 it body, 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 collected and collected.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:

coin.tscn (last line)
[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.

coin.gd (excerpt)
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).

  1. Add a CanvasLayer as a child of Main in main.tscn and name it HUD.
  2. Add a Label as a child of HUD and name it ScoreLabel. Set Text to Coins: 0, Layout → Transform → Position to 840, 24, Size to 280, 48, Horizontal Alignment to Right, and Theme Overrides → Font Sizes → Font Size to 32.

Connect a signal in code

Right-click Main → "Attach Script" to create res://main.gd, and write the following:

main.gd
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 the coins group. 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 @onready gets its value right after the node is ready. $HUD/ScoreLabel means "my child HUD's child, ScoreLabel."
Connect in the editor, or in code?

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)

  1. Use Scene → New Scene to create an Area2D root and name it Enemy.
  2. Add child nodes Sprite2D (Texture: enemy.svg) and CollisionShape2D (New RectangleShape2D, Size 44, 36, Position 0, 4).
  3. Under Enemy's Collision, set Layer to only 4 (enemy) and Mask to only 2 (player).
  4. Save it as res://enemy.tscn and attach the following script, res://enemy.gd, to Enemy.
enemy.gd
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 than patrol_distance away, we flip direction.
  • 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 writing connect("body_entered", ...), but this way Godot catches a misspelled signal name before the game even runs.
  • We toggle $Sprite2D.flip_h so 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:

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 in start_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.tscn structure
Main (Node2D)  … main.gd
├─ Title (Label)
├─ TileMapLayer
├─ Player (player.tscn)
├─ Coin – Coin6 (coin.tscn)
├─ Enemy (enemy.tscn)
├─ Enemy2 (enemy.tscn)
└─ HUD (CanvasLayer)
    └─ ScoreLabel (Label)
main.gd open in the script editor. The Scene dock on the left lists Main, TileMapLayer, Player, Coin through Coin6, Enemy, Enemy2, HUD, and ScoreLabel
main.gd and the scene tree. The icon next to each coin shows that a signal is connected

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.

Try it
  • 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 whether score equals the number of coins.
  • Guess what happens if you delete the collected.emit() line in coin.gd, then try it.

Common pitfalls

SymptomCause and fix
Coins don't disappear when touchedOne 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 upThe 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 startCheck 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

If you hand this lesson's work to 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.

This is Godot 4.6. Connect the body_entered signal of the root Coin (Area2D) in coin.tscn to _on_body_entered in coin.gd. In _on_body_entered, emit the collected signal and then call queue_free(). In main.gd, connect the collected signal of the coins in the "coins" group in code, count the score, and show it in HUD/ScoreLabel.
Create enemy.tscn as an Area2D. It should walk back and forth by patrol_distance to the left and right of its starting position, and call respawn() when it touches the player (a body that has respawn()). Set Layer to 4 and Mask to 2.
  • 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 .gd and .tscn files, 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's body_entered tells 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 name and emit it with name.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

All lessons in the series (11)
  1. Lesson 1: Installing Godot and setting up AI tools
  2. Lesson 2: Nodes and scenes
  3. Lesson 3: GDScript basics
  4. Lesson 4: Input and player movement
  5. Lesson 5: Gravity, jumping, and tilemaps
  6. Lesson 6: Signals, coins, and enemiesYou are here
  7. Lesson 7: UI and screen transitions
  8. Lesson 8: Sound and game feel
  9. Lesson 9: Letting AI playtest your game
  10. Lesson 10: Exporting and publishing
  11. Lesson 11: Bonus: one-prompt games by genre