Godot state machine advanced

From thedivergentai/GD-Agentic-Skills · View interactive version

Godot state machine advanced is an AI agent skill from the GitHub repository thedivergentai/GD-Agentic-Skills. Expert blueprint for hierarchical finite state machines (HSM) and pushdown automata for complex AI/character behaviors. Covers state stacks, sub-states, transition validation, and state context passing. Use when basic FSMs are insufficient OR implementing layered AI. Keywords state machine, HSM, hie

How to use this skill

Skill file

Available Scripts

[hsm_hierarchical_base.gd](scripts/hsm_hierarchical_base.gd)

Advanced HSM base delegator for propagating physics and input to sub-states.

[hsm_pushdown_stack.gd](scripts/hsm_pushdown_stack.gd)

Professional Pushdown Automata for interruptive state (Pause/Menu) stacking.

[hsm_state_context.gd](scripts/hsm_state_context.gd)

Decoupled context object pattern for passing persistent data between states.

[hsm_transition_guard.gd](scripts/hsm_transition_guard.gd)

Expert transition validation logic to prevent illegal state changes.

[hsm_animation_syncer.gd](scripts/hsm_animation_syncer.gd)

Automated Logic-to-AnimationTree syncing with state-based travel logic.

[hsm_concurrent_logic.gd](scripts/hsm_concurrent_logic.gd)

Orchestration for parallel state machines (e.g., Move + Attack).

[hsm_resource_state_loader.gd](scripts/hsm_resource_state_loader.gd)

Data-driven state definition using custom Godot Resources (.tres).

[hsm_reentry_aware_state.gd](scripts/hsm_reentry_aware_state.gd)

Handling resume-from-stack logic vs fresh entry events.

[hsm_state_history_logger.gd](scripts/hsm_state_history_logger.gd)

Debug ring-buffer for tracking state transition history and stack depth.

[hsm_state_timer_component.gd](scripts/hsm_state_timer_component.gd)

Auto-transition component for finite states like Stun or Dash.

MANDATORY: For hierarchy / pushdown / guards read hsm_hierarchical_base.gd, hsm_pushdown_stack.gd, hsm_transition_guard.gd (plus hsm_logic_state.gd for leaf behaviors).

Decision Tree — Which Machine?

| Need | Choose | MANDATORY scripts |

|------|--------|------------------------|

| Few exclusive states, no nesting | Flat FSM | hsm_logic_state.gd + thin parent |

| Nested sub-states (Move/Air/Attack children) | HSM | hsm_hierarchical_base.gd |

| Interrupt overlays (stun/menu/dialogue) then resume | Pushdown | hsm_pushdown_stack.gd + hsm_reentry_aware_state.gd |

| Parallel concerns (locomotion + weapon) | Concurrent | hsm_concurrent_logic.gd |

| Pick best action by score each tick | Utility cost polling | Expert pattern §3 + hsm_transition_guard.gd |

NEVER Do (Expert State Rules)

Hierarchy & Delegation

Transitions & Lifecycle

Architecture & Context

Implementation — Scripts Are Source of Truth

Do NOT copy inline HierarchicalState / push_state samples. Prior body double-exit()ed and ignored resume messages.

MANDATORY route:

Pushdown contract (from script — single exit, resume msg):

# See hsm_pushdown_stack.gd — do not reimplement
func push_state(state_path: String, msg: Dictionary = {}) -> void: ...
func pop_state() -> void:
    # old.exit(); stack.back().enter({"is_resume": true})
    pass

Expert State Machine Patterns

1. HSM Visualizer (Debug Tool)

Use a specialized Control node with _draw() to visualize the current state stack/hierarchy in the viewport for immediate debugging [3, 11].

class_name HSMVisualizer extends Control
@export var state_machine: Node

func _draw() -> void:
    var font := ThemeDB.fallback_font
    var pos := Vector2(20, 20)
    # Recursively draw active state names...
    draw_string(font, pos, "Active: " + state_machine.current_state.name)

2. State-Based Audio (Decoupled)

Avoid hardcoding audio.play() inside state enter() methods. Use a syncer that listens to state_changed and maps state names to AudioStream resources [12, 13].

class_name StateAudioSyncer extends Node
@export var state_machine: Node
@export var audio_map: Dictionary # { "Jump": preload("jump.wav") }

func _ready() -> void:
    state_machine.state_changed.connect(_on_state_changed)

func _on_state_changed(_old, new_state: Node):
    if audio_map.has(new_state.name):
        $AudioPlayer.stream = audio_map[new_state.name]
        $AudioPlayer.play()

3. Transition Cost (Utility AI)

Enable states to evaluate their own "weight" based on context. The StateMachine polls sibling costs and transitions to the lowest-cost behavior [17, 18].

# CostState.gd (Base)
func get_cost(context: Dictionary) -> float:
    return 10.0 # Default weight

# UtilityStateMachine.gd
func _physics_process(_d: float) -> void:
    var best_state: Node = current_state
    var low_cost: float = INF
    for child in get_children():
        var cost = child.get_cost(context)
        if cost < low_cost:
            low_cost = cost
            best_state = child
    if best_state != current_state:
        transition_to(best_state.name)

Deep recipes (on demand)

LLM-ignorance rule: if a general agent would not know it before reading, it lives here or in scripts/ — never delete, only move.

| Topic | Reference |

|-------|-----------|

| State contract + routing | hsm-implementation-cookbook.md |

Reference

Progressive disclosure: open Official Documentation links only when researching a specific API; load Related Skills when routing to a peer domain — do not preload the whole lattice.

Official Documentation

Related Skills

Prerequisites
Complements
Downstream / consumers
Master
Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.