Логотип Godot State Machine Advanced

Godot State Machine Advanced

Сообщество
thedivergentai
godot-state-machine-advanced

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.

Обзор

Издательthedivergentai
РепозиторийGD-Agentic-Skills
Название навыкаgodot-state-machine-advanced
Звёзды
782
Форки
48
Файлы в комплекте
14
ЛицензияLGPL-3.0
Ссылки
  • Инструкции в формате Markdown

    Модель загружает файл SKILL.md по мере необходимости, поэтому токены расходуются только при подходящем запросе.

  • Работает с любой большой языковой моделью

    Навыки ИИ — это обычный Markdown, а не код для конкретного поставщика, поэтому они работают с GPT, Claude, Gemini, Grok и локальными моделями.

  • Файлы в комплекте: 14

    Скрипты, шаблоны и справочные материалы, которые модель может читать во время работы. Файлы доступны только для чтения и никогда не выполняются.

  • Открытый исходный код

    Издатель навыка на GitHub — thedivergentai. Перед установкой изучите исходные материалы.

Установка

Установите навык ИИ Godot State Machine Advanced в TypingMind, чтобы использовать его с любой LLM, или добавьте его в другой агент, который умеет читать SKILL.md.

1

Установка в TypingMind

TypingMind устанавливает навык прямо из его папки на GitHub: читает SKILL.md, собирает файлы ресурсов и сохраняет результат локально.

  1. Откройте приложение и перейдите в раздел «Плагины → Навыки».
  2. Выберите «Установить из GitHub».
  3. Вставьте указанную ниже ссылку на папку навыка и подтвердите установку.
    https://github.com/thedivergentai/GD-Agentic-Skills/tree/main/skills/godot-state-machine-advanced
  4. Включите навык в каждом чате, где хотите его использовать.
Плагины → Навыки → Добавить навык → По ссылке GitHub, затем вставьте ссылку на папку и нажмите «Продолжить».
2

Установка в другом агенте

Любой агент с поддержкой формата Agent Skills может использовать этот навык — скопируйте папку в каталог навыков этого агента.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/thedivergentai/GD-Agentic-Skills.git /tmp/GD-Agentic-Skills
mkdir -p .claude/skills
cp -r /tmp/GD-Agentic-Skills/skills/godot-state-machine-advanced .claude/skills/godot-state-machine-advanced
После копирования перезапустите Claude Code, чтобы загрузить новый навык.

Использование в TypingMind

Включите навык Godot State Machine Advanced в любом чате TypingMind, и дальше модель всё сделает сама. Его название и описание хранятся в системном промпте, а при появлении подходящего запроса модель сама загружает полные инструкции. Вам не нужно вызывать навык вручную, и до фактического использования он не расходует токены.

Модель сама загружает навык Godot State Machine Advanced, как только появляется подходящий для него запрос.

Работает с любой моделью ИИ

Навыки ИИ — это обычные инструкции в Markdown, а не код для конкретного поставщика, поэтому навык Godot State Machine Advanced не привязан к модели, для которой он был создан. Установите его один раз в TypingMind и используйте с GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama или локальной моделью, которую запускаете самостоятельно, — со своими ключами API.

  • Загружается только при необходимости

    Системный промпт содержит только название и описание. Инструкции загружаются при первом подходящем запросе, поэтому неиспользуемый навык не расходует токены.

  • Меняйте модели прямо в чате

    Навык состоит из инструкций, а не кода, поэтому смена модели не нарушает его работу: новая модель читает тот же файл SKILL.md.

Инструкции навыка

Это содержимое файла SKILL.md, которое загружает модель. Прочитайте его перед установкой: навык — это инструкции, которым будет следовать ваша модель.

Available Scripts

hsm_hierarchical_base.gd

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

hsm_pushdown_stack.gd

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

hsm_state_context.gd

Decoupled context object pattern for passing persistent data between states.

hsm_transition_guard.gd

Expert transition validation logic to prevent illegal state changes.

hsm_animation_syncer.gd

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

hsm_concurrent_logic.gd

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

hsm_resource_state_loader.gd

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

hsm_reentry_aware_state.gd

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

hsm_state_history_logger.gd

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

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?

NeedChooseMANDATORY scripts
Few exclusive states, no nestingFlat FSMhsm_logic_state.gd + thin parent
Nested sub-states (Move/Air/Attack children)HSMhsm_hierarchical_base.gd
Interrupt overlays (stun/menu/dialogue) then resumePushdownhsm_pushdown_stack.gd + hsm_reentry_aware_state.gd
Parallel concerns (locomotion + weapon)Concurrenthsm_concurrent_logic.gd
Pick best action by score each tickUtility cost pollingExpert pattern §3 + hsm_transition_guard.gd

NEVER Do (Expert State Rules)

Hierarchy & Delegation

  • NEVER forget to propagate physics/input to children — In an HSM, failing to call child.physics_update() from the parent's _physics_process orphans child logic.
  • NEVER use deep nesting (>3 levels) — Extreme hierarchy creates "State Spaghetti." If logic is that complex, consider a Behavior Tree or Utility AI.

Transitions & Lifecycle

  • NEVER call enter() without a preceding exit() — Skipping exit logic leaves timers, tweens, or audio loops running in the background, causing resource leaks.
  • NEVER modify state during a transition frame — Re-entrant transition_to() calls inside enter() cause recursion crashes. Use call_deferred if immediate sub-transitioning is required.
  • NEVER hardcode state names as strings — Typos like transition_to("Idel") are silent killers. Use class_name based checks OR Constants.

Architecture & Context

  • NEVER use global singletons for state data — Coupling states to GameManager.player_health makes them non-reusable. Pass a Context object.
  • NEVER push states indefinitely — In a Pushdown Automaton, every push_state MUST have a retirement plan (pop_state) to avoid stack overflow.
  • NEVER assume state re-entry is always a fresh start — Resuming from a stack pop should often bypass "Entry SFX/VFX"; use re-entry flags.

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):

gdscript
# 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].

gdscript
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].

gdscript
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].

gdscript
# 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.

TopicReference
State contract + routinghsm-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

  • Using signals — Drive state_changed / transition fan-out so listeners (anim, audio, AI) stay decoupled from enter/exit bodies.
  • Scene organization — Child-node state ownership and signal-up / call-down so the machine orchestrates without sibling hard-coupling.
  • What are Godot classes — Prefer composed state nodes + class_name over deep inheritance trees for layered AI behaviors.
  • Idle and Physics Processing — Why HSMs must forward _physics_process / _process into the active child (or hierarchy) every tick.
  • Using SceneTree — call_deferred transitions avoid re-entrant transition_to() crashes inside enter().
  • Godot notifications — Safe wiring timing for initial enter() relative to _ready and parent caches.
  • Resources — Data-driven state definitions (.tres) for modular AI without baking scripts into every actor.
  • Using AnimationTree — Logic-to-AnimationTree travel when gameplay HSM states map to blend/state-machine graphs.
  • AnimationNodeStateMachinePlayback — travel() / start() APIs used by animation syncers tied to HSM state names.
  • Node — Child lookup, process modes, and lifecycle hooks state nodes inherit as scene-tree citizens.
  • InputEvent — Typed events parents forward into handle_input on the active state.
  • Timer — Finite-duration states (stun, dash) via one-shot timers that emit transition signals.

Related Skills

Prerequisites
  • godot-project-foundations — Scene ownership and project layout conventions every HSM root and child state scene assumes.
  • godot-gdscript-mastery — class_name, typed Dictionaries/payloads, and Callables needed for guards, deferred transitions, and context objects.
  • godot-signal-architecture — Signal-up transition events without circular graphs where states emit and also listen to themselves.
Complements
  • godot-composition — Drop HSM / VSM as a StateComponent under a composition root instead of bloating the actor script.
  • godot-input-handling — Sense-layer sampling; states receive directions/actions via handle_input rather than polling globals.
  • godot-characterbody-2d — Locomotion states call move_and_slide / velocity APIs on the actor passed through context.
  • godot-animation-tree-mastery — Blend trees and AnimationNodeStateMachine graphs that HSM syncers travel into by state name.
  • godot-resource-data-patterns — Tunable state Resources (speeds, stun durations, AI weights) separate from runtime Node lifecycle.
  • godot-2d-animation — Sprite / AnimationPlayer presentation when a lighter sync path than a full AnimationTree is enough.
Downstream / consumers
  • godot-combat-system — Hit-stun, attack windup, and death stacks are classic pushdown / HSM consumers on fighters.
  • godot-ability-system — Cast, channel, and cooldown phases map cleanly to guarded transitions and timed states.
  • godot-turn-system — Turn phases and interrupt stacks reuse pushdown / concurrent machine orchestration patterns.
  • godot-dialogue-system — Cutscene and dialogue overlays push over gameplay states and must pop without losing context.
Master
  • godot-master — Library router and mirrored module entry; open when discovering which Domain Skill owns a cross-cutting architecture concern.

Файлы в комплекте

Модель читает эти файлы по мере необходимости, пока навык загружен. Они доступны только для чтения и никогда не выполняются.

Часто задаваемые вопросы

Что делает навык ИИ Godot State Machine Advanced?

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.

Зачем использовать Godot State Machine Advanced в TypingMind?

Потому что вы устанавливаете навык один раз и используете его с любой моделью. Godot State Machine Advanced — это обычный текст в формате Markdown, а не код для конкретного поставщика, поэтому один и тот же навык работает с GPT-5, Claude, Gemini, Grok или локальной моделью. Вы можете менять модель прямо во время чата, и навык продолжит работать. TypingMind использует ваши собственные ключи API, поэтому вы платите поставщикам напрямую, а не оформляете подписку с оплатой за каждое место. Ваши навыки и чаты остаются в вашем собственном хранилище.

Как установить Godot State Machine Advanced в TypingMind?

В TypingMind откройте «Плагины → Навыки → Установить из GitHub» и вставьте https://github.com/thedivergentai/GD-Agentic-Skills/tree/main/skills/godot-state-machine-advanced. TypingMind прочитает файл SKILL.md, включит сопутствующие файлы в пакет и установит навык, который можно включать отдельно для каждого чата.

Какие модели ИИ могут использовать Godot State Machine Advanced?

Любая модель, которую вы подключите в TypingMind. Навыки ИИ — это обычные инструкции в формате Markdown, а не код для конкретного поставщика, поэтому GPT, Claude, Gemini, Grok и локальные модели могут загружать этот навык, когда запрос ему соответствует.

Со сколькими моделями ИИ можно использовать Godot State Machine Advanced?

С любым количеством. В TypingMind вы можете использовать Godot State Machine Advanced с любой моделью, которая поддерживает навыки, в том числе с GPT, Claude, Gemini, Grok, DeepSeek, Mistral и Llama. Для этого вы используете собственные ключи API.

Бесплатен ли навык ИИ Godot State Machine Advanced?

Да. Навык опубликован на GitHub по лицензии LGPL-3.0. Издатель — thedivergentai. Вы платите только своему поставщику ИИ за использованные токены.

Что такое навыки ИИ?

Навык ИИ — это набор инструкций, которыми модель ИИ может пользоваться каждый раз, когда ей нужно выполнить конкретную задачу. Он соответствует открытому формату Agent Skills: файл SKILL.md с названием и описанием, а также любые скрипты, шаблоны или справочные файлы, которые могут понадобиться модели. Модель читает инструкции, только когда ваш запрос соответствует навыку, поэтому установленный навык ничего не стоит, пока не используется.

Чем навыки ИИ отличаются от плагинов и серверов MCP?

Плагин или сервер MCP даёт модели новые инструменты, которые она может вызывать: при вызове где-то выполняется код и возвращает результат. Навык ИИ, напротив, даёт модели знания и описывает порядок действий: как подойти к задаче, какие шаги выполнить и каким должен быть хороший результат. Навыки — это обычный текст в формате Markdown, поэтому им не нужны сервер, ключ API или среда выполнения, и они работают с любой моделью.

Все

Создайте своё рабочее пространство с ИИ прямо сейчас

Подпишитесь на нашу рассылку, чтобы узнавать о новых функциях и предстоящих розыгрышах 👇