Lesson 5 of 9 · 23m
Input, UI, and Game State Without Spaghetti
Route input through project-defined actions, keep UI in canvas layers, and separate transient input state from authoritative game state.
Input bugs rarely arrive as input bugs. They arrive as "the attack fired while I was typing," "the pause menu still moves the player," or "controller support is different on export." The root cause is usually that input state, UI focus, and game state were never separated. Godot provides the primitives; you still have to choose the architecture.
Input actions are the contract
Define actions in Project Settings and query those actions, not physical keys:
func _physics_process(delta: float) -> void:
var direction := Input.get_vector("move_left", "move_right", "move_up", "move_down")
velocity = direction * speed
move_and_slide()This indirection gives you keyboard, controller, and remapping support. Checking KEY_W directly looks faster in a prototype and becomes a platform-specific migration later.
Choose the right input callback
Use _input for systems that must see input before UI, _unhandled_input for gameplay after controls have had a chance to consume events, and control callbacks such as gui_input for UI elements:
func _unhandled_input(event: InputEvent) -> void:
if event.is_action_pressed("interact"):
try_interact()The distinction prevents gameplay from reacting while the player is renaming a save file or navigating a menu with a controller.
UI belongs in layers, not the moving world
CanvasLayer keeps interface elements independent of world transforms:
Main
├── World
└── UI (CanvasLayer)
├── HUD
├── PauseMenu
└── DialogueBoxWhen get_tree().paused = true, nodes process according to process mode. Configure structure instead of sprinkling checks everywhere:
PauseMenu.process_mode = Node.PROCESS_MODE_ALWAYS
Player.process_mode = Node.PROCESS_MODE_PAUSABLEOne piece of state, one owner
"Is the inventory open?" sounds trivial until input, animation, saving, and networking disagree. Give authoritative state one owner:
class_name GameState
extends Node
enum Mode { EXPLORE, DIALOGUE, PAUSED, INVENTORY }
var mode: Mode = Mode.EXPLORETranslate mode into input rules explicitly. Boolean piles such as is_paused, is_in_menu, is_talking, and can_move drift into contradictory combinations.
Field notes
Input.is_action_pressedpolls current state;event.is_action_pressedhandles a discrete event.- UI focus can consume keys before gameplay sees them; test controller focus neighbors.
- Touch controls should feed the same action abstraction, not a second movement system.
- Mouse capture, window focus, and browser behavior differ enough that focus-loss pause needs explicit design.
- Input buffering belongs in gameplay code with timestamps, not in the input map.
Was this lesson helpful?