Chuyển đến nội dung

Bài 26 · UI, Audio and Animation

Control Nodes and Containers

Build menus and HUDs in Godot 4 with Control nodes: Label, Button, anchors, offsets, VBoxContainer, HBoxContainer, MarginContainer, GridContainer, size flags and signals, with layout stand-ins.

Menus, health bars, inventories and dialogue boxes are all made from Control nodes, Godot's user interface family. Controls look like 2D nodes but add layout: anchors, margins, minimum sizes and containers that arrange their children automatically. Learning containers well is the difference between a UI that breaks at a new resolution and one that adapts.

Godot cannot run on this site, so node trees and scripts are read-only; the runnable blocks are Python stand-ins that reproduce the layout maths. Next in the chapter: AnimationPlayer and tweens.

The Control family

Control is the base class. The ones you use daily:

  • Display: Label, RichTextLabel (BBCode), TextureRect, ColorRect, ProgressBar, TextureProgressBar.
  • Input: Button, CheckBox, OptionButton, LineEdit, TextEdit, Slider, SpinBox.
  • Layout: HBoxContainer, VBoxContainer, GridContainer, MarginContainer, PanelContainer, CenterContainer, ScrollContainer, TabContainer, HFlowContainer.

Put UI under a CanvasLayer if it must stay fixed while the 2D camera moves. A HUD is typically a CanvasLayer with a Control root set to Full Rect.

Anchors and offsets

A Control's rectangle is defined relative to its parent with four anchors (each 0 to 1: the fraction of the parent's size) plus four offsets (pixels from those anchor points). Anchors (0,0,1,1) mean "stretch with the parent". Anchors (1,0,1,0) pin to the top-right corner. Use the Layout menu in the toolbar for presets: Top Left, Center, Full Rect, Bottom Wide and so on. In code, call set_anchors_and_offsets_preset(Control.PRESET_FULL_RECT).

Python Stand-in (Python, not Godot): anchors plus offsets give the rectangle

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The button keeps its size and its 16-pixel gap to the corner in every window size.

Containers decide the layout

A container takes over its children's position and size, so you stop setting them. Key containers:

  • VBoxContainer / HBoxContainer: a column or row with separation pixels between children.
  • MarginContainer: adds padding via theme constants (margin_left, etc.).
  • GridContainer: set columns; children flow into cells.
  • CenterContainer: centers one child.
  • PanelContainer: a background panel plus padding from the theme.
  • ScrollContainer: scroll bars when the content is bigger.

Inside a container each child controls its share through size flags: Fill (stretch to the cell), Expand (ask for spare space) and Shrink Begin/Center/End. Two children with Expand split the spare space equally; size_flags_stretch_ratio weights it. custom_minimum_size sets the smallest size a control may have.

GDSCRIPT
extends Control

func _ready() -> void:
	var column := VBoxContainer.new()
	column.add_theme_constant_override("separation", 12)
	add_child(column)

	var title := Label.new()
	title.text = "Main Menu"
	column.add_child(title)

	for item in ["Play", "Options", "Quit"]:
		var button := Button.new()
		button.text = item
		button.custom_minimum_size = Vector2(220, 48)
		button.pressed.connect(_on_button_pressed.bind(item))
		column.add_child(button)

func _on_button_pressed(item: String) -> void:
	match item:
		"Play": get_tree().change_scene_to_file("res://levels/level_1.tscn")
		"Options": print("open options")
		"Quit": get_tree().quit()
Python Stand-in (Python, not Godot): how an HBoxContainer splits spare width

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The icon stays at its minimum, and the remaining width is shared 2:1 between label and value.

Focus, keyboard and gamepad navigation

Buttons take keyboard and gamepad focus automatically. Call grab_focus() on the first button when a menu opens so the arrow keys and "ui_accept" work immediately. The focus_neighbor_* properties override the default order. Always test menus without a mouse, because console and Steam Deck players use none.

Signals and data binding

Controls communicate with signals: Button.pressed, Slider.value_changed, LineEdit.text_submitted, OptionButton.item_selected. Keep UI in its own scene and let game objects emit signals the UI listens to, instead of the player holding references to labels. Update a health bar by connecting to a health_changed signal and setting ProgressBar.value, not by polling every frame.

Python Stand-in (Python, not Godot): a tiny signal and a health bar that listens

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. Which node keeps a HUD fixed on screen while a Camera2D moves?

    A CanvasLayer draws independently of the camera, so its children do not scroll with the world.
  2. 2. Anchors (1,1,1,1) with negative offsets do what?

    All anchors at 1 attach every edge to the bottom-right corner; negative offsets move the edges back inside.
  3. 3. What does the Expand size flag do inside an HBoxContainer?

    Expand children share leftover space, weighted by size_flags_stretch_ratio.
  4. 4. Why call grab_focus() on the first button of a menu?

    Focus lets arrow keys or the D-pad move between buttons.

Summary

  • Controls use anchors plus offsets; presets in the Layout menu cover most cases.
  • Containers arrange children automatically; size flags and minimum sizes shape the result.
  • Put HUDs under a CanvasLayer; build UI as its own scene.
  • Connect to signals instead of polling, and make menus usable by keyboard and gamepad.

Next: AnimationPlayer and Tweens

Theo dõi tiến độ của bạn

Tạo tài khoản miễn phí để đánh dấu bài đã học và tiếp tục từ chỗ bạn dừng lại trên mọi thiết bị.