[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6KREKGCQMVDV8WX7HWX8BZG":3,"skill-same:01M6KREKGCQMVDV8WX7HWX8BZG":67},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":33,"linkOnly":34,"markdownContent":35,"markdownBody":36,"frontMatter":37,"refName":38,"commitSha":39,"skillDirectory":40,"forksCount":41,"repositoryHtmlUrl":42,"repositoryHomepageUrl":6,"ownerHtmlUrl":43,"ownerBlogUrl":44,"ownerDescription":45,"updatedAt":46,"install":47,"resources":60},"01M6KREKGCQMVDV8WX7HWX8BZG","state-machine",null,"Use when building a state machine or refactoring logic into one — enum, node, and resource-based FSM patterns with trade-offs. Not for adding states to an existing one","jame581\u002FGodotPrompter","jame581","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F21112138?v=4","01M6KR3KEQ9Z30WVJRR2E2ZVXE","Jan Mesarč","01M6KR3KJVRMPDSMASQPBCBVK3",964,"MIT","https:\u002F\u002Fgithub.com\u002Fjame581\u002FGodotPrompter\u002Fblob\u002Fmaster\u002Fskills\u002Fstate-machine\u002FSKILL.md",[],[19,20,21,22,23,24,25,26,27,28,29,30,31,32],"machine","state","state machine","trade-offs","implementing","use","with","trade","state machines","fsm","node","patterns","godot","when","2026-11-10 10:12:30",false,"---\nname: state-machine\ndescription: Use when building a state machine or refactoring logic into one — enum, node, and resource-based FSM patterns with trade-offs. Not for adding states to an existing one\n---\n\n# State Machines in Godot 4.3+\n\nChoose the right FSM pattern for your complexity level. All examples target Godot 4.3+ with no deprecated APIs.\n\n> **Related skills:** **player-controller** for movement state integration, **ai-navigation** for AI state patterns, **resource-pattern** for resource-based state configuration, **animation-system** for AnimationTree states driven by FSM, **dialogue-system** for dialogue flow as a state machine, **ability-system** for caster state gating (casting\u002Fstunned), **limboai** for the LimboAI addon's HSM (`BTState`) if you need a behavior tree alongside your FSM, **beehave** for a GDScript-only BT alternative.\n\n> **When to reach for an addon:** This skill covers the built-in FSM patterns (enum, node-based, resource-based). If your agent needs a full behavior tree, see **limboai** (C++ + HSM, Godot 4.6+) or **beehave** (pure GDScript, Godot 4.1+) instead.\n\n---\n\n## 1. Approach Comparison\n\n| Approach       | Complexity | Best For                              |\n|----------------|------------|---------------------------------------|\n| Enum-Based     | Low        | Simple objects, fewer than 5 states   |\n| Node-Based     | Medium     | Characters with complex behavior      |\n| Resource-Based | High       | Data-driven or editor-configurable AI |\n\nWhen you recommend one, name the approach you rejected and the factor that decided it (state count, independent concerns, designer editing) — \"node-based, not an enum with `match`, because seven states with their own enter\u002Fexit logic outgrow one script\". A pick with no named alternative cannot be overruled.\n\n---\n\n## 2. Approach 1: Enum-Based (Simplest)\n\nUse when you have a small number of states and no significant enter\u002Fexit logic.\n\n### GDScript\n\n```gdscript\nextends CharacterBody2D\n\nenum State { IDLE, PATROL, CHASE, ATTACK }\n\n@export var patrol_range: float = 200.0\n@export var chase_range: float = 300.0\n@export var attack_range: float = 50.0\n@export var speed: float = 80.0\n\nvar current_state: State = State.IDLE\nvar patrol_target: Vector2 = Vector2.ZERO\n\n@onready var player: Node2D = get_tree().get_first_node_in_group(\"player\")\n\n\nfunc _physics_process(delta: float) -> void:\n\tmatch current_state:\n\t\tState.IDLE:\n\t\t\t_state_idle()\n\t\tState.PATROL:\n\t\t\t_state_patrol()\n\t\tState.CHASE:\n\t\t\t_state_chase()\n\t\tState.ATTACK:\n\t\t\t_state_attack()\n\n\tmove_and_slide()\n\n\nfunc _state_idle() -> void:\n\tvelocity = Vector2.ZERO\n\tif _player_in_range(chase_range):\n\t\tcurrent_state = State.CHASE\n\telif randf() \u003C 0.005:\n\t\tpatrol_target = global_position + Vector2(randf_range(-patrol_range, patrol_range), 0.0)\n\t\tcurrent_state = State.PATROL\n\n\nfunc _state_patrol() -> void:\n\tvar direction := (patrol_target - global_position)\n\tif direction.length() \u003C 4.0:\n\t\tcurrent_state = State.IDLE\n\t\treturn\n\tvelocity = direction.normalized() * speed\n\tif _player_in_range(chase_range):\n\t\tcurrent_state = State.CHASE\n\n\nfunc _state_chase() -> void:\n\tif not is_instance_valid(player):\n\t\tcurrent_state = State.IDLE\n\t\treturn\n\tif _player_in_range(attack_range):\n\t\tcurrent_state = State.ATTACK\n\t\treturn\n\tif not _player_in_range(chase_range):\n\t\tcurrent_state = State.PATROL\n\t\treturn\n\tvelocity = (player.global_position - global_position).normalized() * speed\n\n\nfunc _state_attack() -> void:\n\tvelocity = Vector2.ZERO\n\tif not _player_in_range(attack_range):\n\t\tcurrent_state = State.CHASE\n\n\nfunc _player_in_range(range: float) -> bool:\n\tif not is_instance_valid(player):\n\t\treturn false\n\treturn global_position.distance_to(player.global_position) \u003C= range\n```\n\n### C# Equivalent\n\n```csharp\nusing Godot;\n\npublic partial class SimpleEnemy : CharacterBody2D\n{\n    private enum State { Idle, Patrol, Chase, Attack }\n\n    [Export] public float PatrolRange { get; set; } = 200f;\n    [Export] public float ChaseRange  { get; set; } = 300f;\n    [Export] public float AttackRange { get; set; } = 50f;\n    [Export] public float Speed       { get; set; } = 80f;\n\n    private State _currentState = State.Idle;\n    private Vector2 _patrolTarget = Vector2.Zero;\n    private Node2D _player;\n\n    public override void _Ready()\n    {\n        _player = GetTree().GetFirstNodeInGroup(\"player\") as Node2D;\n    }\n\n    public override void _PhysicsProcess(double delta)\n    {\n        switch (_currentState)\n        {\n            case State.Idle:   StateIdle();   break;\n            case State.Patrol: StatePatrol(); break;\n            case State.Chase:  StateChase();  break;\n            case State.Attack: StateAttack(); break;\n        }\n        MoveAndSlide();\n    }\n\n    private void StateIdle()\n    {\n        Velocity = Vector2.Zero;\n        if (PlayerInRange(ChaseRange))\n        {\n            _currentState = State.Chase;\n        }\n        else if (GD.Randf() \u003C 0.005f)\n        {\n            _patrolTarget = GlobalPosition + new Vector2((float)GD.RandRange(-PatrolRange, PatrolRange), 0f);\n            _currentState = State.Patrol;\n        }\n    }\n\n    private void StatePatrol()\n    {\n        var direction = _patrolTarget - GlobalPosition;\n        if (direction.Length() \u003C 4f) { _currentState = State.Idle; return; }\n        Velocity = direction.Normalized() * Speed;\n        if (PlayerInRange(ChaseRange)) _currentState = State.Chase;\n    }\n\n    private void StateChase()\n    {\n        if (!IsInstanceValid(_player)) { _currentState = State.Idle; return; }\n        if (PlayerInRange(AttackRange)) { _currentState = State.Attack; return; }\n        if (!PlayerInRange(ChaseRange)) { _currentState = State.Patrol; return; }\n        Velocity = (_player.GlobalPosition - GlobalPosition).Normalized() * Speed;\n    }\n\n    private void StateAttack()\n    {\n        Velocity = Vector2.Zero;\n        if (!PlayerInRange(AttackRange)) _currentState = State.Chase;\n    }\n\n    private bool PlayerInRange(float range) =>\n        IsInstanceValid(_player) && GlobalPosition.DistanceTo(_player.GlobalPosition) \u003C= range;\n}\n```\n\n> **When to upgrade away from enum-based:**\n> - Enter\u002Fexit logic starts duplicating across state methods\n> - Animation sync requires explicit enter\u002Fexit hooks\n> - The `match`\u002F`switch` block grows beyond ~100 lines\n\n---\n\n## 3. Approach 2: Node-Based (Recommended for Characters)\n\nEach state is its own node. The `StateMachine` node delegates input and process calls to whichever state is active, and states trigger transitions by name.\n\n### Scene Tree\n\n```\nPlayer (CharacterBody2D)\n└── StateMachine (Node)\n    ├── Idle  (State)\n    ├── Run   (State)\n    ├── Jump  (State)\n    └── Attack (State)\n```\n\n### State Base Class\n\n**GDScript (`state.gd`)**\n\n```gdscript\nclass_name State\nextends Node\n\n## Populated by StateMachine._ready()\nvar entity: CharacterBody2D\nvar state_machine: StateMachine\n\n\n## Called when this state becomes active.\nfunc enter() -> void:\n\tpass\n\n\n## Called when this state is deactivated.\nfunc exit() -> void:\n\tpass\n\n\n## Mirrors _process. Return a state name string to transition, or \"\" to stay.\nfunc update(delta: float) -> String:\n\treturn \"\"\n\n\n## Mirrors _physics_process. Return a state name string to transition, or \"\".\nfunc physics_update(delta: float) -> String:\n\treturn \"\"\n\n\n## Mirrors _unhandled_input.\nfunc handle_input(event: InputEvent) -> String:\n\treturn \"\"\n```\n\n**C# (`State.cs`)**\n\n```csharp\nusing Godot;\n\npublic partial class State : Node\n{\n    \u002F\u002F\u002F Populated by StateMachine._Ready()\n    public CharacterBody2D Entity { get; set; }\n    public StateMachine StateMachine { get; set; }\n\n    public virtual void Enter() { }\n    public virtual void Exit() { }\n    public virtual string Update(double delta) => string.Empty;\n    public virtual string PhysicsUpdate(double delta) => string.Empty;\n    public virtual string HandleInput(InputEvent @event) => string.Empty;\n}\n```\n\n### StateMachine Class\n\n**GDScript (`state_machine.gd`)**\n\n```gdscript\nclass_name StateMachine\nextends Node\n\n@export var initial_state: State\n\nvar current_state: State\nvar states: Dictionary = {}\n\n\nfunc _ready() -> void:\n\tfor child in get_children():\n\t\tif child is State:\n\t\t\tstates[child.name] = child\n\t\t\tchild.entity = owner as CharacterBody2D\n\t\t\tchild.state_machine = self\n\n\tif initial_state:\n\t\tcurrent_state = initial_state\n\t\tcurrent_state.enter()\n\n\nfunc _unhandled_input(event: InputEvent) -> void:\n\tvar next := current_state.handle_input(event)\n\tif next:\n\t\ttransition_to(next)\n\n\nfunc _process(delta: float) -> void:\n\tvar next := current_state.update(delta)\n\tif next:\n\t\ttransition_to(next)\n\n\nfunc _physics_process(delta: float) -> void:\n\tvar next := current_state.physics_update(delta)\n\tif next:\n\t\ttransition_to(next)\n\n\nfunc transition_to(state_name: String) -> void:\n\tif not states.has(state_name):\n\t\tpush_error(\"StateMachine: unknown state '%s'\" % state_name)\n\t\treturn\n\tcurrent_state.exit()\n\tcurrent_state = states[state_name]\n\tcurrent_state.enter()\n```\n\n**C# (`StateMachine.cs`)**\n\n```csharp\nusing System.Collections.Generic;\nusing Godot;\n\npublic partial class StateMachine : Node\n{\n    [Export] public State InitialState { get; set; }\n\n    public State CurrentState { get; private set; }\n    private readonly Dictionary\u003Cstring, State> _states = new();\n\n    public override void _Ready()\n    {\n        foreach (var child in GetChildren())\n        {\n            if (child is State state)\n            {\n                _states[state.Name] = state;\n                state.Entity = Owner as CharacterBody2D;\n                state.StateMachine = this;\n            }\n        }\n\n        if (InitialState != null)\n        {\n            CurrentState = InitialState;\n            CurrentState.Enter();\n        }\n    }\n\n    public override void _UnhandledInput(InputEvent @event)\n    {\n        var next = CurrentState.HandleInput(@event);\n        if (!string.IsNullOrEmpty(next)) TransitionTo(next);\n    }\n\n    public override void _Process(double delta)\n    {\n        var next = CurrentState.Update(delta);\n        if (!string.IsNullOrEmpty(next)) TransitionTo(next);\n    }\n\n    public override void _PhysicsProcess(double delta)\n    {\n        var next = CurrentState.PhysicsUpdate(delta);\n        if (!string.IsNullOrEmpty(next)) TransitionTo(next);\n    }\n\n    public void TransitionTo(string stateName)\n    {\n        if (!_states.TryGetValue(stateName, out var next))\n        {\n            GD.PushError($\"StateMachine: unknown state '{stateName}'\");\n            return;\n        }\n        CurrentState.Exit();\n        CurrentState = next;\n        CurrentState.Enter();\n    }\n}\n```\n\n### Concrete Example: IdleState\n\n**GDScript (`idle_state.gd`)**\n\n```gdscript\nclass_name IdleState\nextends State\n\n\nfunc enter() -> void:\n\tentity.get_node(\"AnimationPlayer\").play(\"idle\")\n\n\nfunc physics_update(delta: float) -> String:\n\tif not entity.is_on_floor():\n\t\treturn \"Jump\"\n\tif Input.get_axis(\"move_left\", \"move_right\") != 0.0:\n\t\treturn \"Run\"\n\treturn \"\"\n\n\nfunc handle_input(event: InputEvent) -> String:\n\tif event.is_action_pressed(\"jump\") and entity.is_on_floor():\n\t\treturn \"Jump\"\n\tif event.is_action_pressed(\"attack\"):\n\t\treturn \"Attack\"\n\treturn \"\"\n```\n\n---\n\n## 4. Approach 3: Resource-Based (Data-Driven)\n\nUse when designers need to configure states in the Godot Inspector without modifying code.\n\n### StateData Resource\n\n```gdscript\nclass_name StateData\nextends Resource\n\n@export var state_name: String = \"\"\n@export var animation_name: String = \"\"\n@export var move_speed: float = 0.0\n@export var can_transition_to: Array[String] = []\n```\n\nExport an `Array[StateData]` on your AI controller. Designers populate each entry in the Inspector — no code changes needed to tune behavior or add states. The runtime reads `can_transition_to` to validate transitions and picks `animation_name` \u002F `move_speed` for each active state.\n\n```csharp\nusing Godot;\n\n[GlobalClass]\npublic partial class StateData : Resource\n{\n    [Export] public string StateName { get; set; } = string.Empty;\n    [Export] public string AnimationName { get; set; } = string.Empty;\n    [Export] public float MoveSpeed { get; set; } = 0f;\n    [Export] public Godot.Collections.Array\u003Cstring> CanTransitionTo { get; set; } = new();\n}\n```\n\nAttach an `Array[StateData]` export on your AI controller class (`[Export] public Godot.Collections.Array\u003CStateData> States`). At runtime, look up the active `StateData` by `StateName` and read `AnimationName` \u002F `MoveSpeed` to drive behavior; use `CanTransitionTo` to guard `TransitionTo` calls.\n\n---\n\n## 5. Hierarchical and Parallel State Machines\n\nWhen a flat FSM grows beyond ~8 states or spans multiple concerns (movement + combat + animation), split into **hierarchical** machines (states own sub-state machines, e.g. `OnGround` containing `Idle\u002FWalk\u002FRun`) or **parallel** machines (independent FSMs for movement, combat, animation running side-by-side). Both keep state counts additive instead of multiplicative.\n\nSee [references\u002Fhierarchical-and-parallel.md](references\u002Fhierarchical-and-parallel.md) for full scene trees, `HierarchicalState` base class, parallel-machine character example, and a \"which to choose\" comparison table — GDScript and C# for each.\n\n---\n\n## 6. Decision Flowchart\n\n```\nStart\n  │\n  ▼\nFewer than 5 states?\n  ├─ Yes ──────────────────────────────────► Enum-Based\n  └─ No\n       │\n       ▼\n     Multiple independent concerns\n     (movement + combat + animation)?\n       ├─ Yes ──────────────────────────────► Parallel State Machines\n       └─ No\n            │\n            ▼\n          States naturally nest\n          (sub-states within states)?\n            ├─ Yes ────────────────────────► Hierarchical State Machine\n            └─ No\n                 │\n                 ▼\n               Designers need to configure\n               states in the Inspector?\n                 ├─ Yes ──────────────────► Resource-Based\n                 └─ No ──────────────────► Node-Based\n```\n\n---\n\n## 7. Implementation Checklist\n\n- [ ] Chose the approach that matches actual complexity (enum \u002F node \u002F resource)\n- [ ] Named the approach rejected and the deciding factor\n- [ ] Every state has explicit `enter()` and `exit()` methods (or equivalent)\n- [ ] All transitions are named explicitly — no implicit fallthrough between states\n- [ ] Animations are started in `enter()` and cleaned up in `exit()` where needed\n- [ ] No circular transition loops that could cause infinite recursion in a single frame\n- [ ] Flat FSM is replaced with hierarchical or parallel when states exceed ~8 or span multiple concerns\n- [ ] Parallel state machines don't modify the same state (e.g., both setting velocity) — one concern per machine\n","# State Machines in Godot 4.3+\n\nChoose the right FSM pattern for your complexity level. All examples target Godot 4.3+ with no deprecated APIs.\n\n> **Related skills:** **player-controller** for movement state integration, **ai-navigation** for AI state patterns, **resource-pattern** for resource-based state configuration, **animation-system** for AnimationTree states driven by FSM, **dialogue-system** for dialogue flow as a state machine, **ability-system** for caster state gating (casting\u002Fstunned), **limboai** for the LimboAI addon's HSM (`BTState`) if you need a behavior tree alongside your FSM, **beehave** for a GDScript-only BT alternative.\n\n> **When to reach for an addon:** This skill covers the built-in FSM patterns (enum, node-based, resource-based). If your agent needs a full behavior tree, see **limboai** (C++ + HSM, Godot 4.6+) or **beehave** (pure GDScript, Godot 4.1+) instead.\n\n---\n\n## 1. Approach Comparison\n\n| Approach       | Complexity | Best For                              |\n|----------------|------------|---------------------------------------|\n| Enum-Based     | Low        | Simple objects, fewer than 5 states   |\n| Node-Based     | Medium     | Characters with complex behavior      |\n| Resource-Based | High       | Data-driven or editor-configurable AI |\n\nWhen you recommend one, name the approach you rejected and the factor that decided it (state count, independent concerns, designer editing) — \"node-based, not an enum with `match`, because seven states with their own enter\u002Fexit logic outgrow one script\". A pick with no named alternative cannot be overruled.\n\n---\n\n## 2. Approach 1: Enum-Based (Simplest)\n\nUse when you have a small number of states and no significant enter\u002Fexit logic.\n\n### GDScript\n\n```gdscript\nextends CharacterBody2D\n\nenum State { IDLE, PATROL, CHASE, ATTACK }\n\n@export var patrol_range: float = 200.0\n@export var chase_range: float = 300.0\n@export var attack_range: float = 50.0\n@export var speed: float = 80.0\n\nvar current_state: State = State.IDLE\nvar patrol_target: Vector2 = Vector2.ZERO\n\n@onready var player: Node2D = get_tree().get_first_node_in_group(\"player\")\n\n\nfunc _physics_process(delta: float) -> void:\n\tmatch current_state:\n\t\tState.IDLE:\n\t\t\t_state_idle()\n\t\tState.PATROL:\n\t\t\t_state_patrol()\n\t\tState.CHASE:\n\t\t\t_state_chase()\n\t\tState.ATTACK:\n\t\t\t_state_attack()\n\n\tmove_and_slide()\n\n\nfunc _state_idle() -> void:\n\tvelocity = Vector2.ZERO\n\tif _player_in_range(chase_range):\n\t\tcurrent_state = State.CHASE\n\telif randf() \u003C 0.005:\n\t\tpatrol_target = global_position + Vector2(randf_range(-patrol_range, patrol_range), 0.0)\n\t\tcurrent_state = State.PATROL\n\n\nfunc _state_patrol() -> void:\n\tvar direction := (patrol_target - global_position)\n\tif direction.length() \u003C 4.0:\n\t\tcurrent_state = State.IDLE\n\t\treturn\n\tvelocity = direction.normalized() * speed\n\tif _player_in_range(chase_range):\n\t\tcurrent_state = State.CHASE\n\n\nfunc _state_chase() -> void:\n\tif not is_instance_valid(player):\n\t\tcurrent_state = State.IDLE\n\t\treturn\n\tif _player_in_range(attack_range):\n\t\tcurrent_state = State.ATTACK\n\t\treturn\n\tif not _player_in_range(chase_range):\n\t\tcurrent_state = State.PATROL\n\t\treturn\n\tvelocity = (player.global_position - global_position).normalized() * speed\n\n\nfunc _state_attack() -> void:\n\tvelocity = Vector2.ZERO\n\tif not _player_in_range(attack_range):\n\t\tcurrent_state = State.CHASE\n\n\nfunc _player_in_range(range: float) -> bool:\n\tif not is_instance_valid(player):\n\t\treturn false\n\treturn global_position.distance_to(player.global_position) \u003C= range\n```\n\n### C# Equivalent\n\n```csharp\nusing Godot;\n\npublic partial class SimpleEnemy : CharacterBody2D\n{\n    private enum State { Idle, Patrol, Chase, Attack }\n\n    [Export] public float PatrolRange { get; set; } = 200f;\n    [Export] public float ChaseRange  { get; set; } = 300f;\n    [Export] public float AttackRange { get; set; } = 50f;\n    [Export] public float Speed       { get; set; } = 80f;\n\n    private State _currentState = State.Idle;\n    private Vector2 _patrolTarget = Vector2.Zero;\n    private Node2D _player;\n\n    public override void _Ready()\n    {\n        _player = GetTree().GetFirstNodeInGroup(\"player\") as Node2D;\n    }\n\n    public override void _PhysicsProcess(double delta)\n    {\n        switch (_currentState)\n        {\n            case State.Idle:   StateIdle();   break;\n            case State.Patrol: StatePatrol(); break;\n            case State.Chase:  StateChase();  break;\n            case State.Attack: StateAttack(); break;\n        }\n        MoveAndSlide();\n    }\n\n    private void StateIdle()\n    {\n        Velocity = Vector2.Zero;\n        if (PlayerInRange(ChaseRange))\n        {\n            _currentState = State.Chase;\n        }\n        else if (GD.Randf() \u003C 0.005f)\n        {\n            _patrolTarget = GlobalPosition + new Vector2((float)GD.RandRange(-PatrolRange, PatrolRange), 0f);\n            _currentState = State.Patrol;\n        }\n    }\n\n    private void StatePatrol()\n    {\n        var direction = _patrolTarget - GlobalPosition;\n        if (direction.Length() \u003C 4f) { _currentState = State.Idle; return; }\n        Velocity = direction.Normalized() * Speed;\n        if (PlayerInRange(ChaseRange)) _currentState = State.Chase;\n    }\n\n    private void StateChase()\n    {\n        if (!IsInstanceValid(_player)) { _currentState = State.Idle; return; }\n        if (PlayerInRange(AttackRange)) { _currentState = State.Attack; return; }\n        if (!PlayerInRange(ChaseRange)) { _currentState = State.Patrol; return; }\n        Velocity = (_player.GlobalPosition - GlobalPosition).Normalized() * Speed;\n    }\n\n    private void StateAttack()\n    {\n        Velocity = Vector2.Zero;\n        if (!PlayerInRange(AttackRange)) _currentState = State.Chase;\n    }\n\n    private bool PlayerInRange(float range) =>\n        IsInstanceValid(_player) && GlobalPosition.DistanceTo(_player.GlobalPosition) \u003C= range;\n}\n```\n\n> **When to upgrade away from enum-based:**\n> - Enter\u002Fexit logic starts duplicating across state methods\n> - Animation sync requires explicit enter\u002Fexit hooks\n> - The `match`\u002F`switch` block grows beyond ~100 lines\n\n---\n\n## 3. Approach 2: Node-Based (Recommended for Characters)\n\nEach state is its own node. The `StateMachine` node delegates input and process calls to whichever state is active, and states trigger transitions by name.\n\n### Scene Tree\n\n```\nPlayer (CharacterBody2D)\n└── StateMachine (Node)\n    ├── Idle  (State)\n    ├── Run   (State)\n    ├── Jump  (State)\n    └── Attack (State)\n```\n\n### State Base Class\n\n**GDScript (`state.gd`)**\n\n```gdscript\nclass_name State\nextends Node\n\n## Populated by StateMachine._ready()\nvar entity: CharacterBody2D\nvar state_machine: StateMachine\n\n\n## Called when this state becomes active.\nfunc enter() -> void:\n\tpass\n\n\n## Called when this state is deactivated.\nfunc exit() -> void:\n\tpass\n\n\n## Mirrors _process. Return a state name string to transition, or \"\" to stay.\nfunc update(delta: float) -> String:\n\treturn \"\"\n\n\n## Mirrors _physics_process. Return a state name string to transition, or \"\".\nfunc physics_update(delta: float) -> String:\n\treturn \"\"\n\n\n## Mirrors _unhandled_input.\nfunc handle_input(event: InputEvent) -> String:\n\treturn \"\"\n```\n\n**C# (`State.cs`)**\n\n```csharp\nusing Godot;\n\npublic partial class State : Node\n{\n    \u002F\u002F\u002F Populated by StateMachine._Ready()\n    public CharacterBody2D Entity { get; set; }\n    public StateMachine StateMachine { get; set; }\n\n    public virtual void Enter() { }\n    public virtual void Exit() { }\n    public virtual string Update(double delta) => string.Empty;\n    public virtual string PhysicsUpdate(double delta) => string.Empty;\n    public virtual string HandleInput(InputEvent @event) => string.Empty;\n}\n```\n\n### StateMachine Class\n\n**GDScript (`state_machine.gd`)**\n\n```gdscript\nclass_name StateMachine\nextends Node\n\n@export var initial_state: State\n\nvar current_state: State\nvar states: Dictionary = {}\n\n\nfunc _ready() -> void:\n\tfor child in get_children():\n\t\tif child is State:\n\t\t\tstates[child.name] = child\n\t\t\tchild.entity = owner as CharacterBody2D\n\t\t\tchild.state_machine = self\n\n\tif initial_state:\n\t\tcurrent_state = initial_state\n\t\tcurrent_state.enter()\n\n\nfunc _unhandled_input(event: InputEvent) -> void:\n\tvar next := current_state.handle_input(event)\n\tif next:\n\t\ttransition_to(next)\n\n\nfunc _process(delta: float) -> void:\n\tvar next := current_state.update(delta)\n\tif next:\n\t\ttransition_to(next)\n\n\nfunc _physics_process(delta: float) -> void:\n\tvar next := current_state.physics_update(delta)\n\tif next:\n\t\ttransition_to(next)\n\n\nfunc transition_to(state_name: String) -> void:\n\tif not states.has(state_name):\n\t\tpush_error(\"StateMachine: unknown state '%s'\" % state_name)\n\t\treturn\n\tcurrent_state.exit()\n\tcurrent_state = states[state_name]\n\tcurrent_state.enter()\n```\n\n**C# (`StateMachine.cs`)**\n\n```csharp\nusing System.Collections.Generic;\nusing Godot;\n\npublic partial class StateMachine : Node\n{\n    [Export] public State InitialState { get; set; }\n\n    public State CurrentState { get; private set; }\n    private readonly Dictionary\u003Cstring, State> _states = new();\n\n    public override void _Ready()\n    {\n        foreach (var child in GetChildren())\n        {\n            if (child is State state)\n            {\n                _states[state.Name] = state;\n                state.Entity = Owner as CharacterBody2D;\n                state.StateMachine = this;\n            }\n        }\n\n        if (InitialState != null)\n        {\n            CurrentState = InitialState;\n            CurrentState.Enter();\n        }\n    }\n\n    public override void _UnhandledInput(InputEvent @event)\n    {\n        var next = CurrentState.HandleInput(@event);\n        if (!string.IsNullOrEmpty(next)) TransitionTo(next);\n    }\n\n    public override void _Process(double delta)\n    {\n        var next = CurrentState.Update(delta);\n        if (!string.IsNullOrEmpty(next)) TransitionTo(next);\n    }\n\n    public override void _PhysicsProcess(double delta)\n    {\n        var next = CurrentState.PhysicsUpdate(delta);\n        if (!string.IsNullOrEmpty(next)) TransitionTo(next);\n    }\n\n    public void TransitionTo(string stateName)\n    {\n        if (!_states.TryGetValue(stateName, out var next))\n        {\n            GD.PushError($\"StateMachine: unknown state '{stateName}'\");\n            return;\n        }\n        CurrentState.Exit();\n        CurrentState = next;\n        CurrentState.Enter();\n    }\n}\n```\n\n### Concrete Example: IdleState\n\n**GDScript (`idle_state.gd`)**\n\n```gdscript\nclass_name IdleState\nextends State\n\n\nfunc enter() -> void:\n\tentity.get_node(\"AnimationPlayer\").play(\"idle\")\n\n\nfunc physics_update(delta: float) -> String:\n\tif not entity.is_on_floor():\n\t\treturn \"Jump\"\n\tif Input.get_axis(\"move_left\", \"move_right\") != 0.0:\n\t\treturn \"Run\"\n\treturn \"\"\n\n\nfunc handle_input(event: InputEvent) -> String:\n\tif event.is_action_pressed(\"jump\") and entity.is_on_floor():\n\t\treturn \"Jump\"\n\tif event.is_action_pressed(\"attack\"):\n\t\treturn \"Attack\"\n\treturn \"\"\n```\n\n---\n\n## 4. Approach 3: Resource-Based (Data-Driven)\n\nUse when designers need to configure states in the Godot Inspector without modifying code.\n\n### StateData Resource\n\n```gdscript\nclass_name StateData\nextends Resource\n\n@export var state_name: String = \"\"\n@export var animation_name: String = \"\"\n@export var move_speed: float = 0.0\n@export var can_transition_to: Array[String] = []\n```\n\nExport an `Array[StateData]` on your AI controller. Designers populate each entry in the Inspector — no code changes needed to tune behavior or add states. The runtime reads `can_transition_to` to validate transitions and picks `animation_name` \u002F `move_speed` for each active state.\n\n```csharp\nusing Godot;\n\n[GlobalClass]\npublic partial class StateData : Resource\n{\n    [Export] public string StateName { get; set; } = string.Empty;\n    [Export] public string AnimationName { get; set; } = string.Empty;\n    [Export] public float MoveSpeed { get; set; } = 0f;\n    [Export] public Godot.Collections.Array\u003Cstring> CanTransitionTo { get; set; } = new();\n}\n```\n\nAttach an `Array[StateData]` export on your AI controller class (`[Export] public Godot.Collections.Array\u003CStateData> States`). At runtime, look up the active `StateData` by `StateName` and read `AnimationName` \u002F `MoveSpeed` to drive behavior; use `CanTransitionTo` to guard `TransitionTo` calls.\n\n---\n\n## 5. Hierarchical and Parallel State Machines\n\nWhen a flat FSM grows beyond ~8 states or spans multiple concerns (movement + combat + animation), split into **hierarchical** machines (states own sub-state machines, e.g. `OnGround` containing `Idle\u002FWalk\u002FRun`) or **parallel** machines (independent FSMs for movement, combat, animation running side-by-side). Both keep state counts additive instead of multiplicative.\n\nSee [references\u002Fhierarchical-and-parallel.md](references\u002Fhierarchical-and-parallel.md) for full scene trees, `HierarchicalState` base class, parallel-machine character example, and a \"which to choose\" comparison table — GDScript and C# for each.\n\n---\n\n## 6. Decision Flowchart\n\n```\nStart\n  │\n  ▼\nFewer than 5 states?\n  ├─ Yes ──────────────────────────────────► Enum-Based\n  └─ No\n       │\n       ▼\n     Multiple independent concerns\n     (movement + combat + animation)?\n       ├─ Yes ──────────────────────────────► Parallel State Machines\n       └─ No\n            │\n            ▼\n          States naturally nest\n          (sub-states within states)?\n            ├─ Yes ────────────────────────► Hierarchical State Machine\n            └─ No\n                 │\n                 ▼\n               Designers need to configure\n               states in the Inspector?\n                 ├─ Yes ──────────────────► Resource-Based\n                 └─ No ──────────────────► Node-Based\n```\n\n---\n\n## 7. Implementation Checklist\n\n- [ ] Chose the approach that matches actual complexity (enum \u002F node \u002F resource)\n- [ ] Named the approach rejected and the deciding factor\n- [ ] Every state has explicit `enter()` and `exit()` methods (or equivalent)\n- [ ] All transitions are named explicitly — no implicit fallthrough between states\n- [ ] Animations are started in `enter()` and cleaned up in `exit()` where needed\n- [ ] No circular transition loops that could cause infinite recursion in a single frame\n- [ ] Flat FSM is replaced with hierarchical or parallel when states exceed ~8 or span multiple concerns\n- [ ] Parallel state machines don't modify the same state (e.g., both setting velocity) — one concern per machine\n",{"name":5,"description":7},"master","60c28fdc40706a24576731e9fb3508b9c95258ad","skills\u002Fstate-machine",63,"https:\u002F\u002Fgithub.com\u002Fjame581\u002FGodotPrompter","https:\u002F\u002Fgithub.com\u002Fjame581","https:\u002F\u002Fjanmesarc.online\u002F","Software engineer. My biggest passion is game development.","2026-11-14 20:45:49",{"source":8,"skillName":5,"commands":48,"prompt":58,"zipAvailable":59},[49,52,55],{"tool":50,"command":51},"npx","npx skills add jame581\u002FGodotPrompter --skill state-machine",{"tool":53,"command":54},"bunx","bunx skills add jame581\u002FGodotPrompter --skill state-machine",{"tool":56,"command":57},"pnpm","pnpm dlx skills add jame581\u002FGodotPrompter --skill state-machine","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fjame581\u002FGodotPrompter\u002Fblob\u002Fmaster\u002Fskills\u002Fstate-machine\u002FSKILL.md",true,[61],{"path":62,"resourceType":63,"resourceTypeDesc":64,"sizeBytes":65,"sourceHtmlUrl":66},"references\u002Fhierarchical-and-parallel.md","REFERENCE","参考文档",5241,"https:\u002F\u002Fgithub.com\u002Fjame581\u002FGodotPrompter\u002Fblob\u002Fmaster\u002Fskills\u002Fstate-machine\u002Freferences\u002Fhierarchical-and-parallel.md",[68,87,108,133,148,165],{"skillNo":69,"name":70,"nameZh":6,"description":71,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":72,"categories":73,"keywords":74,"publishedAt":33},"01M6KRFE5BR2PSD08ZKDAS66R7","xr-development","Use when building VR\u002FAR\u002FXR applications — OpenXR setup, XROrigin3D, hand tracking, controllers, passthrough, and Meta Quest deployment in Godot 4.3+","https:\u002F\u002Fgithub.com\u002Fjame581\u002FGodotPrompter\u002Fblob\u002Fmaster\u002Fskills\u002Fxr-development\u002FSKILL.md",[],[75,76,32,77,31,78,79,80,81,82,83,24,84,85,86],"xr development","development","deployment","vr","setup","tracking","godot 4","ar","hand","Meta","applications","quest",{"skillNo":88,"name":89,"nameZh":6,"description":90,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":91,"categories":92,"keywords":93,"publishedAt":33},"01M6KRF8GZTG1TAS506MFBSGFC","web-services","Use when a Godot game calls a web server — HTTPRequest, downloads, REST\u002FJSON APIs, auth headers, WebSocketPeer clients, TLS, retries, and keeping secrets out of the build. Not for game networking\u002FRPCs (multiplayer-basics) or browser export (web-export)","https:\u002F\u002Fgithub.com\u002Fjame581\u002FGodotPrompter\u002Fblob\u002Fmaster\u002Fskills\u002Fweb-services\u002FSKILL.md",[],[94,95,96,97,98,99,100,101,24,32,31,102,103,104,105,106,107],"web services","web","services","tls","retries","calling","auth","downloads","clients","headers","secrets","json","build","REST",{"skillNo":109,"name":110,"nameZh":6,"description":111,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":112,"categories":113,"keywords":114,"publishedAt":33},"01M6KRF38Q4WSKAYFS56PG87T0","web-export","Use when shipping a Godot game to the browser — Web export preset options, threads vs no-threads and COOP\u002FCOEP headers, hosting on itch.io or your own server, PWA, JavaScriptBridge, user:\u002F\u002F persistence, audio and input limits, and load size","https:\u002F\u002Fgithub.com\u002Fjame581\u002FGodotPrompter\u002Fblob\u002Fmaster\u002Fskills\u002Fweb-export\u002FSKILL.md",[],[95,115,116,117,32,118,119,120,121,103,122,123,124,125,126,127,128,129,24,130,131,132],"export","web export","threads","limits","shipping","size","options","server","hosting","input","preset","browser","game","io","load","pwa","Audio","Coop",{"skillNo":134,"name":135,"nameZh":6,"description":136,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":137,"categories":138,"keywords":139,"publishedAt":33},"01M6KREYFETEBH62ZTN6EZH2X3","using-godot-prompter","Bootstrap skill — establishes how to find and use GodotPrompter skills, with platform-specific tool mapping","https:\u002F\u002Fgithub.com\u002Fjame581\u002FGodotPrompter\u002Fblob\u002Fmaster\u002Fskills\u002Fusing-godot-prompter\u002FSKILL.md",[],[31,140,141,142,25,24,143,144,145,146,147],"using godot prompter","bootstrap","find","tool","platform","mapping","how","how to",{"skillNo":149,"name":150,"nameZh":6,"description":151,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":152,"categories":153,"keywords":154,"publishedAt":33},"01M6KRER5G7EQWKGAFN8QJKQ69","tween-animation","Use when implementing tweens — property animation, method tweening, chaining, parallel sequences, easing, and common UI\u002Fgameplay motion recipes","https:\u002F\u002Fgithub.com\u002Fjame581\u002FGodotPrompter\u002Fblob\u002Fmaster\u002Fskills\u002Ftween-animation\u002FSKILL.md",[],[155,156,157,158,159,160,161,162,23,163,164,32,24],"tween animation","Animation","parallel","gameplay","chaining","ui","recipes","common","motion","sequences",{"skillNo":166,"name":167,"nameZh":6,"description":168,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":169,"categories":170,"keywords":171,"publishedAt":33},"01M6KREE370Y80QK838PCRBA0S","shader-basics","Use when implementing shaders — Godot shader language, visual shaders, common visual recipes, and post-processing effects","https:\u002F\u002Fgithub.com\u002Fjame581\u002FGodotPrompter\u002Fblob\u002Fmaster\u002Fskills\u002Fshader-basics\u002FSKILL.md",[],[172,173,174,161,32,31,175,176,177,178,162,179,180,24,23,181],"shader","shader basics","basics","language","post-processing","shaders","post","visual","effects","processing"]