A State Machine in GDScript
A player who can idle, run, jump, fall, dash and get hurt, or an enemy who patrols, chases and attacks, quickly turns into a tangle of booleans: is_jumping, is_dashing, can_attack, was_on_floor... and bugs like "dashing while dead". A finite state machine (FSM) fixes that: the object is in exactly one state at a time, each state has its own update code, and transitions are explicit. (The idea itself is covered in Game Development Fundamentals.)
Godot projects use two styles:
| Style | Looks like | Good for |
|---|---|---|
enum + match |
one script, enum State {...} and a match state: block |
small enemies, doors, UI flows, 3–5 states |
| node-based | a StateMachine node with one child node (and script) per state |
players and bosses with many states, each with enter/exit logic |
Style 1: enum and match
An enemy that waits, chases the player when they come close, bites when in reach, and chases again when the player escapes:
extends Node2D
# frames: 90
enum State { IDLE, CHASE, ATTACK }
const DETECT := 60.0
const REACH := 12.0
const SPEED := 90.0
var state := State.IDLE
var cooldown := 0.0
var enemy_x := 0.0
var player_x := 100.0
func change_state(new_state: State) -> void:
if new_state == state:
return
print("frame ", Engine.get_physics_frames(), ": ", State.keys()[state], " -> ", State.keys()[new_state],
" (gap ", snappedf(player_x - enemy_x, 0.1), ")")
state = new_state
if state == State.ATTACK:
cooldown = 0.0 # bite as soon as we arrive
func _physics_process(delta: float) -> void:
var frame := Engine.get_physics_frames()
if frame <= 30:
player_x -= 90.0 * delta # the player walks toward the enemy
if frame == 75:
player_x += 40.0 # ... and dashes away
var gap := player_x - enemy_x
match state:
State.IDLE:
if gap < DETECT:
change_state(State.CHASE)
State.CHASE:
enemy_x += SPEED * delta
if gap <= REACH:
change_state(State.ATTACK)
State.ATTACK:
cooldown -= delta
if cooldown <= 0.0:
print("frame ", Engine.get_physics_frames(), ": bite!")
cooldown = 0.5
if gap > REACH * 1.5:
change_state(State.CHASE)frame 27: IDLE -> CHASE (gap 59.5)
frame 57: CHASE -> ATTACK (gap 10.0)
frame 58: bite!
frame 75: ATTACK -> CHASE (gap 50.0)
The essentials:
- All transitions go through
change_state(). That one function is the place for enter/exit work (resetting the cooldown), for logging, and later for playing the right animation. Never assignstatedirectly elsewhere. - Hysteresis: the enemy starts attacking at 12 px but only gives up at 18 px (
REACH * 1.5). With one threshold, a player standing at exactly 12 px makes the enemy flicker between states every frame. State.keys()[state]turns the enum value into its name for debugging.- The typed
var state := State.IDLEandfunc change_state(new_state: State)let the editor warn when you pass a wrong value.
Good up to a handful of states. When the match grows past a screen, or states need their own variables and timers, move to nodes.
Style 2: one node per state
Each state is a node with enter(), exit() and physics_update(); the state machine node forwards the engine callbacks to the current state and swaps states when one emits finished. In a real project the pieces are separate files (state.gd with class_name State, state_machine.gd, idle.gd, run.gd...) and the tree looks like this:
Player (CharacterBody2D)
├── CollisionShape2D
├── AnimatedSprite2D
└── StateMachine (Node) state_machine.gd, initial_state = Idle
├── Idle (Node) idle.gd
├── Run (Node)
├── Jump (Node)
└── Fall (Node)The verified version below fits everything in one script with inner classes, builds the floor and the player in code, and simulates the keyboard with Input.action_press(): press right at frame 10, jump at frame 25, let go of right at frame 60.
extends Node2D
# frames: 80
# ---- the reusable pieces (in a project: state.gd and state_machine.gd) ----
class State extends Node:
signal finished(next_state: StringName)
var body: CharacterBody2D
func enter() -> void: pass
func exit() -> void: pass
func physics_update(_delta: float) -> void: pass
class StateMachine extends Node:
var current: State
func start(body: CharacterBody2D, initial: StringName) -> void:
for child in get_children():
child.body = body
child.finished.connect(_transition)
current = get_node(NodePath(initial))
current.enter()
func _physics_process(delta: float) -> void:
current.physics_update(delta)
func _transition(next: StringName) -> void:
print("frame ", Engine.get_physics_frames(), ": ", current.name, " -> ", next)
current.exit()
current = get_node(NodePath(next))
current.enter()
# ---- the player's states ----
const GRAVITY := 900.0
const SPEED := 120.0
const JUMP := -300.0
class Idle extends State:
func enter() -> void:
body.velocity.x = 0.0
func physics_update(_delta: float) -> void:
body.move_and_slide()
if Input.is_action_just_pressed("jump"):
finished.emit(&"Jump")
elif Input.get_axis("move_left", "move_right") != 0.0:
finished.emit(&"Run")
class Run extends State:
func physics_update(_delta: float) -> void:
body.velocity.x = Input.get_axis("move_left", "move_right") * SPEED
body.move_and_slide()
if Input.is_action_just_pressed("jump"):
finished.emit(&"Jump")
elif body.velocity.x == 0.0:
finished.emit(&"Idle")
class Jump extends State:
func enter() -> void:
body.velocity.y = JUMP
func physics_update(delta: float) -> void:
body.velocity.y += GRAVITY * delta
body.velocity.x = Input.get_axis("move_left", "move_right") * SPEED
body.move_and_slide()
if body.velocity.y >= 0.0:
finished.emit(&"Fall")
class Fall extends State:
func physics_update(delta: float) -> void:
body.velocity.y += GRAVITY * delta
body.velocity.x = Input.get_axis("move_left", "move_right") * SPEED
body.move_and_slide()
if body.is_on_floor():
finished.emit(&"Idle" if body.velocity.x == 0.0 else &"Run")
# ---- test scene: floor, player, simulated input ----
var player: CharacterBody2D
func box(size: Vector2) -> CollisionShape2D:
var cs := CollisionShape2D.new()
var r := RectangleShape2D.new()
r.size = size
cs.shape = r
return cs
func _ready():
for action in ["move_left", "move_right", "jump"]:
InputMap.add_action(action)
var floor := StaticBody2D.new()
floor.add_child(box(Vector2(2000, 20)))
floor.position = Vector2(0, 10)
add_child(floor)
player = CharacterBody2D.new()
player.name = "Player"
player.add_child(box(Vector2(16, 24)))
player.position = Vector2(0, -12)
add_child(player)
var fsm := StateMachine.new()
var states := {"Idle": Idle.new(), "Run": Run.new(), "Jump": Jump.new(), "Fall": Fall.new()}
for state_name in states:
states[state_name].name = state_name
fsm.add_child(states[state_name])
add_child(fsm)
fsm.start(player, &"Idle")
func _physics_process(_delta):
match Engine.get_physics_frames(): # a scripted "player" pressing keys
10: Input.action_press("move_right")
25: Input.action_press("jump")
30: Input.action_release("jump")
60: Input.action_release("move_right")
75: print("end: x=", snappedf(player.position.x, 0.1), " on_floor=", player.is_on_floor())frame 10: Idle -> Run
frame 26: Run -> Jump
frame 46: Jump -> Fall
frame 66: Fall -> Idle
end: x=98.0 on_floor=true
Things to notice:
- States signal up, the machine calls down. A state never reaches into its siblings; it emits
finished(&"Jump"), and the machine decides. Adding aDashstate means one new node and one newemitin the states that can dash. enter()does the one-time work:Jump.enter()sets the jump velocity once,Idle.enter()stops horizontal motion. That is where you would also callsprite.play("jump"), so animations and logic can't get out of sync.- The jump was pressed at frame 25 and the state changed at frame 26. A simulated
action_press()made during a physics frame counts as "just pressed" on the next physics frame, much like a real key press that arrives between frames. - The jump lasted 20 frames up (300 / 900 s = 1/3 s) and 20 down, which you can check by hand: the numbers are deterministic because
_physics_processruns at a fixed rate. - State names are
StringNameliterals (&"Run"), cheap to compare. For safety,@export var initial_state: Stateand typed references between states are common in the multi-file version.
The editor-friendly version of StateMachine usually adds _unhandled_input forwarding and an exported initial state:
class_name StateMachine
extends Node
@export var initial_state: State
@onready var state: State = initial_state
func _ready() -> void:
for child in get_children():
if child is State:
child.finished.connect(_transition_to)
await owner.ready # the Player's _ready has run; its @onready vars exist
state.enter()
func _unhandled_input(event: InputEvent) -> void:
state.handle_input(event)
func _physics_process(delta: float) -> void:
state.physics_update(delta)
func _transition_to(next_path: StringName) -> void:
state.exit()
state = get_node(NodePath(next_path))
state.enter()await owner.ready matters: children are ready before their parents, so without it the states could start before the player has finished its own _ready().
Beyond a single FSM
- Hierarchical states:
Groundedwith sub-statesIdleandRunshare "jump if pressed" code. - Pushdown automata: a stack of states for "pause menu over gameplay" or "stunned, then return to what you were doing".
- AnimationTree has its own
AnimationNodeStateMachinefor animation states; keep gameplay logic in your FSM and let it set the animation tree's conditions or calltravel(). - For complex AI, behaviour trees: the LimboAI addon offers both behaviour trees and hierarchical state machines, and the Game AI course explains when each fits.
Test yourself
Why route every state change through one change_state() function?
- GDScript requires it
- It gives one place for exit/enter work, logging and animation changes, so transitions can't skip that code
- It makes
matchfaster - It avoids using enums
An enemy attacks below 12 px and chases above 12 px. A player standing at 12 px makes it flicker between states. What fixes it?
- Use
_processinstead of_physics_process - Hysteresis: enter ATTACK below 12 px but leave it only above a larger distance, such as 18 px
- Add more states
- Round the distance
In the node-based state machine, how does the Run state ask to switch to Jump?
- It calls
get_parent().get_node("Jump").enter() - It emits its
finishedsignal with&"Jump", and the StateMachine performs the transition - It sets a global variable
- It frees itself