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, hierarchical, pushdown automata, state stack, FSM, AI behavior.
npx skills add https://github.com/thedivergentai/GD-Agentic-Skills --skill godot-state-machine-advanced
Hierarchical states, state stacks, and context passing define complex behavior management.
Advanced HSM base delegator for propagating physics and input to sub-states.
Professional Pushdown Automata for interruptive state (Pause/Menu) stacking.
Decoupled context object pattern for passing persistent data between states.
Expert transition validation logic to prevent illegal state changes.
Automated Logic-to-AnimationTree syncing with state-based travel logic.
Orchestration for parallel state machines (e.g., Move + Attack).
Data-driven state definition using custom Godot Resources (.tres).
Handling resume-from-stack logic vs fresh entry events.
Debug ring-buffer for tracking state transition history and stack depth.
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).
| 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 |
child.physics_update() from the parent's _physics_process orphans child logic.transition_to() calls inside enter() cause recursion crashes. Use call_deferred if immediate sub-transitioning is required.transition_to("Idel") are silent killers. Use class_name based checks OR Constants.GameManager.player_health makes them non-reusable. Pass a Context object.push_state MUST have a retirement plan (pop_state) to avoid stack overflow.> Do NOT copy inline HierarchicalState / push_state samples. Prior body double-exit()ed and ignored resume messages.
MANDATORY route:
enter({"is_resume": true}): hsm_pushdown_stack.gdPushdown 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
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)
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()
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)
> 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 |
> 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.
state_changed / transition fan-out so listeners (anim, audio, AI) stay decoupled from enter/exit bodies.class_name over deep inheritance trees for layered AI behaviors._physics_process / _process into the active child (or hierarchy) every tick.call_deferred transitions avoid re-entrant transition_to() crashes inside enter().enter() relative to _ready and parent caches..tres) for modular AI without baking scripts into every actor.travel() / start() APIs used by animation syncers tied to HSM state names.handle_input on the active state.A set of resources to help me write all kinds of internal communications, using the formats that my company likes to use. Claude should use this skill whenever asked to write some sort of internal communications (status reports, leadership updates, 3P updates, company newsletters, FAQs, incident reports, project updates, etc.).
Extracts and analyzes competitors' ads from ad libraries (Facebook, LinkedIn, etc.) to understand what messaging, problems, and creative approaches are working. Helps inspire and improve your own ad campaigns.
Identifies high-quality leads for your product or service by analyzing your business, searching for target companies, and providing actionable contact strategies. Perfect for sales, business development, and marketing professionals.
Analyzes your recent Claude Code chat history to identify coding patterns, development gaps, and areas for improvement, curates relevant learning resources from HackerNews, and automatically sends a personalized growth report to your Slack DMs.
Complete App Store Optimization (ASO) toolkit for researching, optimizing, and tracking mobile app performance on Apple App Store and Google Play Store
NGS analysis toolkit. BAM to bigWig conversion, QC (correlation, PCA, fingerprints), heatmaps/profiles (TSS, peaks), for ChIP-seq, RNA-seq, ATAC-seq visualization.
Materials science toolkit. Crystal structures (CIF, POSCAR), phase diagrams, band structure, DOS, Materials Project integration, format conversion, for computational materials science.
Transforms vague UI ideas into polished, Stitch-optimized prompts. Enhances specificity, adds UI/UX keywords, injects design system context, and structures output for better generation results.
Take thedivergentai/godot-state-machine-advanced from the repository into ~/.claude/skills for personal
use, or into .claude/skills inside a project.
The agent identifies a skill by the name field in its header. Two skills with the
same name cannot sit side by side — one of them will be ignored.