- How Control nodes differ from Node2D
- Remember values across scenes with an Autoload
- Rebuild the HUD with containers
- Lives, time, clearing the stage, and game over
- Make a title screen
- The result screen and retrying
- Make the title screen the main scene
- Common pitfalls
- Working with AI
- Recap and what's next
In Lesson 6, collecting coins started raising the score, and touching an enemy sent you back to the start. But nothing happens when you collect every coin, and no matter how many times you get hit, the game never ends. In this lesson, we'll build the UI (user interface) and complete one full "loop" of the game: title screen → game → clear or game over screen → play again.
Finished project for Lesson 7: project-lesson07.zip (16 KB)
How Control nodes differ from Node2D
The Sprite2D and CharacterBody2D nodes we've used so far belong to the Node2D family. When you build on-screen UI like buttons, text, and panels, you use the Control family instead (the ones with green icons when you add a node). The Label we used for the score in Lesson 6 is a Control too.
| Node2D family | Control family | |
|---|---|---|
| Main use | Things inside the game world (characters, enemies, floors) | On-screen UI (text, buttons, menus) |
| How position is set | Position (coordinates) | Anchors (where on the screen it sticks) and size |
| How things are arranged | You set the coordinates yourself | Put them in a container and they line up automatically |
| Mouse and keyboard | You write the code yourself | Button clicks, focus, and so on work out of the box |
| Examples | Sprite2D, Area2D, Camera2D | Label, Button, ColorRect, VBoxContainer |
The most important idea in UI is anchors. They decide which part of the parent rectangle a control is attached to: "stick to the top left of the screen," "fill the whole screen," "stretch across the top edge," and so on. Even when the window changes size, the UI follows along without drifting out of place. In the Inspector, under Layout → Anchors Preset, you can pick from the most common shapes. This lesson uses these three:
- Full Rect: fills the whole parent (backgrounds, full-screen layouts)
- Top Wide: sticks to the top edge and stretches all the way across (the HUD bar)
- Center: sits in the middle
The other key idea is containers. A VBoxContainer lines up its children vertically, an HBoxContainer horizontally, a CenterContainer puts its children in the middle, and a MarginContainer adds padding around them. The container decides the position and size of its children, so you don't have to type in coordinates yourself.
Remember values across scenes with an Autoload
In this lesson, we'll switch between three scenes: the title, the game, and the result. The catch is that when you switch scenes, every node in the previous scene is deleted, variables and all. Even if you store the score in main.gd's score, it disappears the moment you move to the result screen.
That's what an Autoload is for. A script you register in Project Settings is created once when the game starts, isn't deleted when you switch scenes, and can be called by name from any script.
- In the FileSystem dock, right-click
res://→ Create New → Script..., set Inherits toNodeand the path tores://game_state.gd, and create it. - Write the following and save.
extends Node
# Register this script as an Autoload named GameState.
# Any scene can use it like GameState.score, and it isn't deleted when the scene changes
# Number of lives at the start of a game
const START_LIVES: int = 3
# Number of coins collected in this run
var score: int = 0
# Lives remaining
var lives: int = START_LIVES
# Whether the last run was cleared (used by the result screen)
var cleared: bool = false
# Time of the last run (seconds)
var last_time: float = 0.0
# Fastest clear time (seconds). 0.0 means there's no record yet
var best_time: float = 0.0
# Call this when starting a new game. Only the best time is kept
func reset() -> void:
score = 0
lives = START_LIVES
cleared = false
last_time = 0.0
# Call this when the game ends. If it was cleared, update the best time
func finish(is_clear: bool, time: float) -> void:
cleared = is_clear
last_time = time
if is_clear and (best_time == 0.0 or time < best_time):
best_time = timeconstdeclares a constant (a value that never changes later). Giving a name to a number you set once and leave alone, like the starting number of lives, means you only have to change one place when you tweak it later.reset()is called when a game starts, andfinish()when it ends. Keeping the ways these values change inside GameState itself makes it easier to follow what changes where.
Next, register this script as an Autoload.
- Open Project → Project Settings... from the menu and select the Autoload tab.
- Click the folder icon to the right of the Path: field and choose
res://game_state.gd. Check that Node Name: saysGameState, then click Add. GameStateis added to the list. If Enable is checked in the Global Variable column, you're done.
Once it's registered, the following lines are written to project.godot. The * in front of the path marks it as "use as a global variable."
[autoload]
GameState="*res://game_state.gd"Now any script can say GameState.score or GameState.reset(). While the game is running, a node called GameState sits under the very top of the scene tree (/root), with the current scene right next to it. Switching scenes only swaps out the current scene, so GameState stays put.
Autoloads are handy, but when you have too many variables that anything can change from anywhere, it gets hard to tell "where did this change?" The trick is to store only the values you need to keep across scenes. Here, that's just the score, lives, result, and best time.
Rebuild the HUD with containers
The information shown during play (score, lives left, and so on) is called the HUD. In Lesson 6, we placed ScoreLabel inside HUD (a CanvasLayer) using coordinates. Children of a CanvasLayer stay in the same spot on screen even when the camera moves. This time we're going up to three readouts, so we'll lay them out again with containers.
- Open
main.tscnand deleteScoreLabelunderHUD. Since we're making a title screen, also delete theTitle(Label) we put in the top left of the stage. - Add a
MarginContaineras a child ofHUDand name itTopBar. In the Inspector, set Layout → Anchors Preset to Top Wide. You now have a bar stretching across the top edge of the screen. - Under
TopBar's Theme Overrides → Constants, set Margin Left to24, Margin Top to16, and Margin Right to24(the padding on the left, top, and right). - Add an
HBoxContaineras a child ofTopBarand name itRow. - Add three
Labelnodes as children ofRowand name themScoreLabel,TimeLabel, andLivesLabel. For all three, set Theme Overrides → Font Sizes → Font Size to32, and under Layout → Container Sizing → Horizontal, check Expand. - Set Horizontal Alignment to Center for
TimeLabeland Right forLivesLabel(leaveScoreLabelat Left). Set their Text toCoins: 0 / 6,Time: 0.0, andLives: 3(the code rewrites these when the game runs).
HUD (CanvasLayer)
└─ TopBar (MarginContainer) … Top Wide
└─ Row (HBoxContainer)
├─ ScoreLabel (Label) … left-aligned
├─ TimeLabel (Label) … centered
└─ LivesLabel (Label) … right-aligned
Children with Expand checked split the width of the HBoxContainer equally. Each of the three labels gets one third of the width and aligns left, center, or right within it, so they line up neatly at the left edge, middle, and right edge of the screen. That layout holds even when the window width changes.
Lives, time, clearing the stage, and game over
Let's set the rules: collect every coin to clear the stage, and get hit by enemies 3 times and it's game over. The faster your clear time, the better your record.
Add a hit signal to the player
To tell Main that "the player touched an enemy," we'll give the player its own signal, just like in Lesson 6. Here's the whole player.gd (what changed is signal hit and the hit.emit() inside respawn()):
extends CharacterBody2D
# Signal emitted when we touch an enemy
signal hit
# 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:
# Announce that we got hit (taking away a life is main.gd's job)
hit.emit()
position = start_position
velocity = Vector2.ZEROThe player only announces "I got hit"; it doesn't know how many lives are left. Counting is Main's job. enemy.gd stays the same as in Lesson 6.
Rewrite main.gd
The score has moved into GameState, so the score variable in main.gd goes away. Replace the whole file with this:
extends Node2D
# Number of coins on the stage (counted in _ready)
var coin_total: int = 0
# Time since the start (seconds)
var time: float = 0.0
# The HUD labels. With @onready, they get filled in right before _ready
@onready var score_label: Label = $HUD/TopBar/Row/ScoreLabel
@onready var time_label: Label = $HUD/TopBar/Row/TimeLabel
@onready var lives_label: Label = $HUD/TopBar/Row/LivesLabel
func _ready() -> void:
# We're starting a new game, so reset the score and lives to their starting values
GameState.reset()
var coins: Array[Node] = get_tree().get_nodes_in_group("coins")
coin_total = coins.size()
# In code, connect the collected signal of every coin in the "coins" group
for coin: Node in coins:
coin.connect("collected", _on_coin_collected)
# Also connect, in code, the hit signal the player emits when it touches an enemy
$Player.connect("hit", _on_player_hit)
update_hud()
func _process(delta: float) -> void:
time += delta
# %.1f is replaced by "the number with one decimal place"
time_label.text = "Time: %.1f" % time
# Called when any coin emits its collected signal
func _on_coin_collected() -> void:
GameState.score += 1
update_hud()
# Collecting every coin clears the stage
if GameState.score == coin_total:
end_game(true)
# Called when the player emits its hit signal
func _on_player_hit() -> void:
GameState.lives -= 1
update_hud()
# When lives reach 0, it's game over
if GameState.lives <= 0:
end_game(false)
func update_hud() -> void:
# %d is replaced by a whole number. For two or more, pass them in a [ ] list
score_label.text = "Coins: %d / %d" % [GameState.score, coin_total]
lives_label.text = "Lives: " + str(GameState.lives)
# End the game and switch to the result screen
func end_game(is_clear: bool) -> void:
GameState.finish(is_clear, time)
# Changing scenes in the middle of physics processing causes an error, so call_deferred puts it off a moment
get_tree().change_scene_to_file.call_deferred("res://result.tscn")- We call
GameState.reset()at the very start of_ready. When you come back with "Play Again," this is also where the score and lives go back to their starting values. coin_totalis the number of coins in the group. Whether you add or remove coins, the "collect them all to clear" check doesn't need to change."Time: %.1f" % timeis string formatting. The%.1fin the string is replaced bytimerounded to one decimal place.%dis for whole numbers; to fill in two or more, pass them in a[ ]list.get_tree().change_scene_to_file("res://result.tscn")switches scenes. The current scene (Main) is removed and replaced by the scene you specify.- When you grab the last coin or touch an enemy, the physics engine is in the middle of working out "what overlapped what." Removing the scene partway through causes an error, so we add
call_deferredto switch "after the current processing finishes."
Make a title screen
Now we'll make a new scene that's nothing but UI.
- Choose Scene → New Scene, and under Create Root Node: in the Scene dock, click User Interface. A
Controlis created as the root; name itTitle. The root's Anchors Preset is already Full Rect (fills the screen). - Add a
ColorRectas a child ofTitleand name itBackground. Set its Anchors Preset to Full Rect and its Color to the same light blue as the game's sky (669ed9). - Add a
CenterContaineras a child ofTitle, name itCenter, and set its Anchors Preset to Full Rect too. - Add a
VBoxContaineras a child ofCenterand name itMenu. Set Theme Overrides → Constants → Separation to24(the spacing between items). - Add these four to
Menu, in order:Label(nameTitleLabel): TextHop Hop Coins, Horizontal Alignment Center, Font Size64TextureRect(nameIcon): Textureicon.svg, Stretch Mode Keep CenteredLabel(nameBestLabel): TextCollect all the coins!, Horizontal Alignment Center, Font Size28Button(nameStartButton): TextStart, Font Size32, Layout → Custom Minimum Size240,64, and Container Sizing → Horizontal set to Shrink Center (so the button doesn't stretch across the full width and sits in the middle)
- Save it as
res://title.tscn.
Title (Control) … title.gd
├─ Background (ColorRect) … Full Rect
└─ Center (CenterContainer) … Full Rect
└─ Menu (VBoxContainer)
├─ TitleLabel (Label)
├─ Icon (TextureRect)
├─ BestLabel (Label)
└─ StartButton (Button)
Connect the button's pressed signal
A button emits the pressed signal when it's pressed. We'll connect it in the editor, just like the coin in Lesson 6.
- Right-click
Title→ Attach Script to createres://title.gd. - Select
StartButton, and in the Signals tab of the dock on the right, double-clickpressed()underBaseButton. - In Connect a Signal to a Method, choose
Titleas the target, check that Receiver Method: is_on_start_button_pressed, and click Connect.
extends Control
@onready var best_label: Label = $Center/Menu/BestLabel
@onready var start_button: Button = $Center/Menu/StartButton
func _ready() -> void:
# GameState isn't deleted when the scene changes, so the record from the last run is still there
if GameState.best_time > 0.0:
best_label.text = "Best time: %.1f s" % GameState.best_time
else:
best_label.text = "Collect all the coins!"
# Giving the button focus lets you press it with the Space or Enter key too
start_button.grab_focus()
# Called when the "Start" button is pressed (connected in the editor's "Signals" tab)
func _on_start_button_pressed() -> void:
get_tree().change_scene_to_file("res://main.tscn")- You receive a button click as a signal that says "I was pressed." A button can be pressed with the mouse or the keyboard, and
pressedfires the same way either way. grab_focus()points keyboard input at that button. A button with focus can be pressed with the Enter key or the Space key.- If a best time has been recorded, we show it. When you come back to the title the second time or later, GameState is still around, so the previous record can be read.
The result screen and retrying
We'll use one result screen for both clearing the stage and game over, just changing what it shows. Building it works almost exactly like the title screen.
- Create a new scene, click User Interface, and name the root
Result. - Just like the title, make
Background(ColorRect, Full Rect, Color navy333d66),Center(CenterContainer, Full Rect), andMenu(VBoxContainer, Separation24). - Add two
Labelnodes toMenu(ResultLabelwith Font Size64andDetailLabelwith Font Size28, both with Horizontal Alignment Center) and twoButtonnodes (RetryButtonwith TextPlay AgainandTitleButtonwith TextBack to Title, both with the same size and settings as the Start button). - Save it as
res://result.tscnand attach the scriptres://result.gdtoResult. - Connect the
pressed()signals ofRetryButtonandTitleButtontoResult's_on_retry_button_pressedand_on_title_button_pressed, respectively.
extends Control
@onready var result_label: Label = $Center/Menu/ResultLabel
@onready var detail_label: Label = $Center/Menu/DetailLabel
@onready var retry_button: Button = $Center/Menu/RetryButton
func _ready() -> void:
# GameState still remembers how the run went
if GameState.cleared:
result_label.text = "Stage Clear!"
detail_label.text = "Time: %.1f s (Best: %.1f s)" % [GameState.last_time, GameState.best_time]
else:
result_label.text = "Game Over"
detail_label.text = "Coins collected: %d" % GameState.score
retry_button.grab_focus()
# "Play Again" button: start the game scene over from the beginning
func _on_retry_button_pressed() -> void:
get_tree().change_scene_to_file("res://main.tscn")
# "Back to Title" button: return to the title screen
func _on_title_button_pressed() -> void:
get_tree().change_scene_to_file("res://title.tscn")This is where the Autoload really shines. main.tscn is already gone, yet reading GameState.cleared and GameState.score tells us how the run went. When "Play Again" loads main.tscn again, the stage starts fresh, and main.gd's _ready resets the score and lives.
Make the title screen the main scene
The scene that opens first when you press F5 (Run Project) is called the main scene. Right now it's main.tscn, so let's change it to the title screen.
- In the FileSystem dock, right-click
title.tscnand choose Set as Main Scene.
You can also change it under Application → Run → Main Scene in Project Settings.... If run/main_scene in project.godot becomes "res://title.tscn", you're all set.
Run it with F5. Press Start on the title screen and the game begins, with the coin count, time, and lives lined up along the top edge. Collect all six coins to get the clear screen, or get hit by enemies three times to get the game over screen; "Play Again" lets you try again. If you clear the stage and then go back to the title, your best time should be displayed.
Here's the flow between scenes so far:
title.tscn ──Start──→ main.tscn ──all coins──→ result.tscn (Stage Clear!)
↑ │ │
│ └──0 lives──→ result.tscn (Game Over)
│ │
└──────────Back to Title───────────────────────┤
main.tscn ←──Play Again───┘
(The whole time, GameState remembers score / lives / best_time)- Set
START_LIVESingame_state.gdto1and see how the tension changes. - Add a "How to play"
Labelto the title screen ("← → to move, Space to jump"). Just put it insideMenuand it lines up automatically. - Drag the edge of the window to resize it. You'll see the HUD and title screen follow their anchors.
Common pitfalls
| Symptom | Cause and fix |
|---|---|
Identifier "GameState" not declared in the current scope. | It isn't registered as an Autoload, or the node name is different. In the Autoload tab, check that the node name is GameState (including upper/lower case) and that Enable is checked. |
Removing a CollisionObject node during a physics callback is not allowed and will cause undesired behavior. at the moment you clear the stage or get a game over | You're switching scenes inside a signal, in the middle of physics processing. Add call_deferred, as in change_scene_to_file.call_deferred(...). |
| Nothing happens when you press a button | The pressed() signal isn't connected. In the Signals tab, check that the target method appears under pressed(). |
| The HUD labels pile up in the top left | If Expand isn't checked under the label's Container Sizing → Horizontal, the labels don't share the width and get squeezed to the left. Check it on all three. |
| The background only covers part of the screen | The ColorRect's Anchors Preset isn't Full Rect. Also check that the parent Title is Full Rect. |
| F5 starts on the stage instead of the title | The main scene is still main.tscn. Use Set as Main Scene on title.tscn. Note that F6 (Run Current Scene) starts from whichever scene is open. |
| On your second play, you start with fewer lives | You aren't calling GameState.reset() in main.gd's _ready. Autoload values stick around until you reset them yourself. |
Working with AI
For UI, decide up front "what goes on which screen, and where" and "which button goes to which screen," and your requests to AI won't drift. Handing over something like the "Screen flow" diagram above as is works well.
- A (chat): it's good at screen layouts, how scene transitions fit together, and writing the scripts. You add the nodes, set the anchors, and register the Autoload in the editor yourself. If things look off, pasting a screenshot makes the problem easier to get across.
- B (Claude Code, etc.): it can write
.tscnandproject.godotfiles too, so it can build the scenes and register the Autoload in one go. But if it rewritesproject.godotwhile the editor is open, the editor may overwrite the change and it's lost. Also, the AI can't see how the UI actually looks. - C (+ MCP): with Godot MCP Pro, the AI can register the Autoload (
add_autoload), set anchors (set_anchor_preset), and connect button signals (connect_signal) inside the editor. You can leave it to run the game, press buttons (click_button_by_text), check the text on screen (assert_screen_text), and look at the result in a screenshot (get_game_screenshot).
Whichever approach you use, play it yourself at the end to check. Text size and color, and how easy the buttons are to press, are things you decide by actually looking and touching.
Recap and what's next
- Build UI from the Control family. Set placement with Anchors Preset (Full Rect, Top Wide, and so on)
- Put children in a container (VBox, HBox, Center, Margin) and they line up automatically
- A node registered as an Autoload isn't deleted when scenes change and can be used by name from anywhere
- Switch scenes with
get_tree().change_scene_to_file(). During physics processing, usecall_deferred - Receive button presses with the
pressedsignal.grab_focus()makes the button pressable from the keyboard - Change the main scene with Set as Main Scene
Now you can play one full "loop" of the game. Next time: sound and game feel. We'll use sound effects, BGM, Tweens, and particles to make grabbing a coin feel great.
Want AI to handle building the UI and checking screen transitions?
With Godot MCP Pro, Claude Code or Cursor can set up Control node anchors and Autoloads inside the editor, run the game, press buttons, and even check the text on screen (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