AnimationTree State Machines
in Godot 4
Godot 4のAnimationTree
ステートマシン完全ガイド
The complete guide to state machines, transitions, blend trees, OneShot, travel() vs conditions — with real GDScript code examples.
ステートマシン、トランジション、ブレンドツリー、OneShot、travel()と条件分岐 — 実践的なGDScriptコード例付きの完全ガイド。
Table of Contents
目次
- Introductionはじめに
- Prerequisites前提条件
- Basic Setup基本セットアップ
- State Machine Basicsステートマシンの基本
- Controlling the State Machine from Codeコードからステートマシンを制御する
- travel() vs Conditionstravel()と条件の使い分け
- Blend Treesブレンドツリー
- Common Node Types主要なノードタイプ
- OneShot Pattern (Attacks, Emotes)OneShotパターン(攻撃・エモート)
- Practical Example: Full Character Controller実践例:キャラクターコントローラー
- Troubleshootingトラブルシューティング
- Automate with Godot MCP ProGodot MCP Proで自動化
1. Introductionはじめに
AnimationTree is Godot 4's system for complex animation blending and state transitions. If you have ever tried to manage multiple animations with AnimationPlayer.play() calls scattered throughout your code, you know how quickly it becomes unmanageable. AnimationTree solves this with a visual graph of states and transitions.
AnimationTreeはGodot 4における複雑なアニメーションブレンディングと状態遷移のためのシステムです。AnimationPlayer.play()の呼び出しをコード中にばらまいて複数のアニメーションを管理しようとした経験があるなら、それがいかに早く手に負えなくなるかご存知でしょう。AnimationTreeはビジュアルな状態とトランジションのグラフでこの問題を解決します。
Despite being incredibly powerful, AnimationTree's official documentation is sparse and often leaves developers guessing. This guide walks through everything from basic setup to advanced blend trees, with real GDScript code you can copy into your project.
AnimationTreeは非常に強力であるにもかかわらず、公式ドキュメントは不十分で、開発者が手探りになることも少なくありません。このガイドでは、基本セットアップから高度なブレンドツリーまで、プロジェクトにそのままコピーできる実践的なGDScriptコードとともに全てを解説します。
State machines, transitions, blend spaces (1D & 2D), OneShot for attacks, travel() vs conditions, and a complete character controller pattern.
ステートマシン、トランジション、ブレンドスペース(1D・2D)、攻撃用OneShot、travel()と条件の使い分け、完全なキャラクターコントローラーパターン。
2. Prerequisites前提条件
Before setting up your AnimationTree, you need:
AnimationTreeをセットアップする前に、以下が必要です:
- An
AnimationPlayernode with at least Idle, Walk, Run, and Jump animations already created - Idle、Walk、Run、Jumpなどのアニメーションが作成済みの
AnimationPlayerノード - The AnimationPlayer must be a sibling or child of the node where you add the AnimationTree (typically both are children of your character root node)
- AnimationPlayerはAnimationTreeを追加するノードの兄弟または子である必要があります(通常、両方ともキャラクターのルートノードの子です)
- Godot 4.x (this guide uses Godot 4 API — the AnimationTree API changed significantly from Godot 3)
- Godot 4.x(このガイドはGodot 4のAPIを使用しています — AnimationTreeのAPIはGodot 3から大きく変更されました)
In Godot 4, AnimationTree.animation_player was replaced by AnimationTree.anim_player. The playback parameter path also changed. If you are migrating from Godot 3, check the official migration guide.
Godot 4ではAnimationTree.animation_playerがAnimationTree.anim_playerに変更されました。playbackのパラメータパスも変わっています。Godot 3から移行する場合は公式移行ガイドを確認してください。
3. Basic Setup基本セットアップ
Setting up an AnimationTree takes four steps:
AnimationTreeのセットアップは4ステップです:
-
Add an AnimationTree nodeAnimationTreeノードを追加
— Add it as a child of your character (e.g.,
CharacterBody2DorCharacterBody3D), alongside your AnimationPlayer. — AnimationPlayerと並べて、キャラクター(例:CharacterBody2DまたはCharacterBody3D)の子として追加します。 -
Set
anim_playeranim_playerを設定 — In the Inspector, point the "Anim Player" property to your AnimationPlayer node. — インスペクターで「Anim Player」プロパティをAnimationPlayerノードに向けます。 -
Set
tree_roottree_rootを設定 — Click the "Tree Root" property in the Inspector and create a newAnimationNodeStateMachine. — インスペクターの「Tree Root」プロパティをクリックして、新しいAnimationNodeStateMachineを作成します。 -
Set
active = trueactive = trueに設定 — Check the "Active" checkbox in the Inspector, or set it in code. — インスペクターで「Active」チェックボックスをオンにするか、コードで設定します。
Your scene tree should look like this:
シーンツリーは以下のようになります:
CharacterBody2D (or CharacterBody3D)
+-- Sprite2D (or Sprite3D)
+-- CollisionShape2D
+-- AnimationPlayer <-- has Idle, Walk, Run, Jump animations
+-- AnimationTree <-- points to AnimationPlayer above
GDScript
# Minimal code setup (usually done via the editor instead):
@onready var anim_tree: AnimationTree = $AnimationTree
func _ready() -> void:
# If you set these in the Inspector, you don't need this code
anim_tree.anim_player = ^"../AnimationPlayer"
anim_tree.tree_root = AnimationNodeStateMachine.new()
anim_tree.active = true
In practice, you almost always configure the AnimationTree in the editor. The code above is shown for completeness, but you typically only need anim_tree.active = true in your script (and even that can be set in the editor).
実際の開発では、ほぼ常にエディタでAnimationTreeを設定します。上記のコードは網羅性のために示していますが、通常はスクリプトでanim_tree.active = trueだけで十分です(これもエディタで設定可能です)。
4. State Machine Basicsステートマシンの基本
A state machine in AnimationTree works on a simple concept: states represent animations, and transitions define the conditions for switching between them.
AnimationTreeのステートマシンはシンプルなコンセプトで動作します:状態(state)はアニメーションを表し、トランジションは状態間の切り替え条件を定義します。
Adding States
状態の追加
Once your AnimationTree's tree_root is an AnimationNodeStateMachine, double-click it in the Inspector to open the state machine editor:
AnimationTreeのtree_rootがAnimationNodeStateMachineに設定されたら、インスペクターでダブルクリックしてステートマシンエディタを開きます:
- Right-click in the graph area and select Add Animation
- グラフエリアを右クリックし、Add Animationを選択
- Choose an animation from your AnimationPlayer (Idle, Walk, Run, Jump, etc.)
- AnimationPlayerからアニメーションを選択(Idle、Walk、Run、Jumpなど)
- Repeat for each animation state you need
- 必要な各アニメーション状態に対して繰り返します
Start is the entry point — the first transition always begins here. End is optional and signals that the state machine has finished (useful for nested state machines).
Startはエントリーポイントです。最初のトランジションは必ずここから始まります。Endはオプションで、ステートマシンの終了を示します(ネストされたステートマシンで有用)。
Adding Transitions
トランジションの追加
To create a transition between two states:
2つの状態間にトランジションを作成するには:
- Click on the source state node
- ソースの状態ノードをクリック
- Drag to the destination state to create a transition arrow
- デスティネーションの状態にドラッグしてトランジション矢印を作成
- Click the transition arrow to configure it in the Inspector
- トランジション矢印をクリックしてインスペクターで設定
Transition Properties
トランジションのプロパティ
| Property | プロパティ | Description | 説明 |
|---|---|---|---|
advance_mode |
Auto — fires when its condition is true. Enabled — always available for travel(). Disabled — blocked. | Auto — 条件がtrueのとき発火。Enabled — travel()で常に利用可能。Disabled — ブロック。 | |
advance_condition |
Name of a boolean parameter (e.g., is_moving). When true, the transition fires automatically. |
ブールパラメータの名前(例:is_moving)。trueのときトランジションが自動発火。 |
|
xfade_time |
Crossfade duration in seconds. Smooth blending between animations. Typical: 0.1 – 0.3s. | クロスフェードの秒数。アニメーション間のスムーズなブレンド。典型的:0.1〜0.3秒。 | |
switch_mode |
Immediate — switch now. Sync — match playback position. AtEnd — wait for current animation to finish. | Immediate — 即座に切替。Sync — 再生位置を合わせる。AtEnd — 現在のアニメーション終了まで待機。 |
A typical setup for a platformer character:
プラットフォーマーキャラクターの典型的なセットアップ:
Start --> Idle
Idle --> Walk (condition: is_moving)
Walk --> Idle (condition: is_idle)
Idle --> Jump (condition: is_jumping)
Walk --> Jump (condition: is_jumping)
Jump --> Fall (condition: is_falling)
Fall --> Idle (condition: is_on_floor, switch_mode: Immediate)
5. Controlling the State Machine from Codeコードからステートマシンを制御する
There are two main ways to drive the state machine: setting condition parameters (automatic transitions) and calling travel() (manual transitions). You can mix both approaches.
ステートマシンを駆動する方法は主に2つあります:条件パラメータの設定(自動トランジション)とtravel()の呼び出し(手動トランジション)です。両方のアプローチを組み合わせることもできます。
extends CharacterBody2D
@onready var anim_tree: AnimationTree = $AnimationTree
@onready var state_machine: AnimationNodeStateMachinePlayback = anim_tree.get("parameters/playback")
func _physics_process(delta: float) -> void:
# ... movement logic here ...
move_and_slide()
_update_animation_parameters()
func _update_animation_parameters() -> void:
# Approach 1: Set condition parameters — transitions fire automatically
anim_tree.set("parameters/conditions/is_moving", velocity.length() > 10.0)
anim_tree.set("parameters/conditions/is_idle", velocity.length() <= 10.0)
anim_tree.set("parameters/conditions/is_on_floor", is_on_floor())
anim_tree.set("parameters/conditions/is_jumping", velocity.y < 0 and not is_on_floor())
anim_tree.set("parameters/conditions/is_falling", velocity.y > 0 and not is_on_floor())
# Approach 2: Use travel() for direct control
# if velocity.length() > 10.0:
# state_machine.travel("Walk")
# else:
# state_machine.travel("Idle")
Parameters follow the pattern parameters/conditions/<condition_name> for conditions set on transitions. The condition name must match the advance_condition you set on the transition in the editor.
パラメータのパターンはparameters/conditions/<condition_name>です(トランジションに設定した条件の場合)。条件名はエディタでトランジションに設定したadvance_conditionと一致する必要があります。
6. travel() vs Conditionsと条件の使い分け
Condition-Based (Recommended for Locomotion)
条件ベース(移動系に推奨)
Set boolean parameters each frame and let the transitions fire automatically. This is more declarative and keeps your code clean. The state machine handles transition logic, crossfades, and edge cases for you.
毎フレームブールパラメータを設定し、トランジションを自動発火させます。より宣言的でコードがクリーンになります。ステートマシンがトランジションロジック、クロスフェード、エッジケースを処理します。
# Declarative: just describe the current state of the world
anim_tree.set("parameters/conditions/is_moving", velocity.length() > 10.0)
anim_tree.set("parameters/conditions/is_on_floor", is_on_floor())
travel() (Recommended for One-Off Actions)
travel()(単発アクションに推奨)
travel() requests a state transition. It respects transition rules — if no valid path exists from the current state to the target, the call is ignored. This makes it safe to call repeatedly. Use it for one-off triggers like attacks, emotes, or cutscene animations.
travel()は状態遷移をリクエストします。トランジションルールを尊重するため、現在の状態からターゲットへの有効なパスがなければ呼び出しは無視されます。繰り返し呼んでも安全です。攻撃、エモート、カットシーンアニメーションなどの単発トリガーに使用します。
# travel() — requests a transition (respects transition rules)
state_machine.travel("Jump")
# Get current state name
var current: StringName = state_machine.get_current_node()
print(current) # "Idle", "Walk", etc.
# Check if travel is possible
var is_playing: bool = state_machine.is_playing()
print(is_playing)
Conditions for continuous states (idle, walk, run, fall). travel() for event-triggered states (attack, dodge, interact). Many projects use both: conditions for locomotion, travel() for combat actions.
条件は連続的な状態(待機、歩行、走行、落下)に。travel()はイベントトリガーの状態(攻撃、回避、インタラクト)に。多くのプロジェクトでは両方を使います:移動は条件、戦闘アクションはtravel()。
7. Blend Treesブレンドツリー
Blend trees allow you to smoothly interpolate between multiple animations based on a continuous value, rather than hard-switching between discrete states. This is perfect for walk/run speed blending and directional movement.
ブレンドツリーは、離散的な状態間のハードスイッチではなく、連続値に基づいて複数のアニメーション間をスムーズに補間できます。歩行/走行速度のブレンドや方向移動に最適です。
BlendSpace1D
A 1D blend between two or more animations along a single axis. Common use: blending Walk and Run based on movement speed.
単一軸に沿った2つ以上のアニメーション間の1Dブレンド。一般的な使用例:移動速度に基づくWalkとRunのブレンド。
In the editor, create a BlendSpace1D node inside your state machine (or as a standalone tree root). Add animation points:
エディタで、ステートマシン内(またはスタンドアロンのツリールートとして)BlendSpace1Dノードを作成します。アニメーションポイントを追加:
# BlendSpace1D setup (in editor):
# Point 0.0 = Walk animation
# Point 1.0 = Run animation
# Control from code:
var speed_factor: float = clamp(velocity.length() / max_speed, 0.0, 1.0)
anim_tree.set("parameters/WalkRun/blend_position", speed_factor)
BlendSpace2D
A 2D blend using two axes. Perfect for 8-directional movement or top-down games where the character can move in any direction.
2軸を使った2Dブレンド。8方向移動やキャラクターが任意の方向に移動できるトップダウンゲームに最適です。
# BlendSpace2D setup (in editor):
# Place animations at positions:
# Idle at (0, 0)
# WalkRight at (1, 0), WalkLeft at (-1, 0)
# WalkUp at (0, -1), WalkDown at (0, 1)
# Diagonals at corners
# Control from code:
var input_dir := Input.get_vector("move_left", "move_right", "move_up", "move_down")
anim_tree.set("parameters/Movement/blend_position", input_dir)
BlendSpace2D supports multiple blend modes: the default triangulation works well for most cases. You can also choose discrete mode (snaps to nearest point) if you want pixel-art-style animation without interpolation.
BlendSpace2Dは複数のブレンドモードをサポートします。デフォルトの三角分割はほとんどの場合うまく機能します。ピクセルアート風の補間なしアニメーションが必要な場合は、離散モード(最寄りのポイントにスナップ)も選択できます。
8. Common Node Types主要なノードタイプ
AnimationTree supports several node types that can be combined to create complex animation behavior:
AnimationTreeは複数のノードタイプをサポートし、組み合わせることで複雑なアニメーション動作を作成できます:
| Node Type | ノードタイプ | Use Case | 用途 |
|---|---|---|---|
AnimationNodeStateMachine |
State machine with transitions. The most common root node. States can be animations or nested state machines. | トランジション付きステートマシン。最も一般的なルートノード。状態はアニメーションまたはネストされたステートマシン。 | |
AnimationNodeBlendSpace1D |
1D blend along one axis. Walk/run speed, aim angle, etc. | 1軸に沿った1Dブレンド。歩行/走行速度、エイム角度など。 | |
AnimationNodeBlendSpace2D |
2D blend using two axes. Directional movement, strafe blending. | 2軸を使った2Dブレンド。方向移動、横歩きブレンド。 | |
AnimationNodeBlendTree |
A graph of blend operations. Combine multiple blend nodes with custom logic. | ブレンド操作のグラフ。複数のブレンドノードをカスタムロジックで組み合わせ。 | |
AnimationNodeAdd2 |
Additive blending. Layer an animation on top of another (e.g., aim offset on top of walk). | 加算ブレンド。アニメーションの上に別のアニメーションを重ねる(例:歩行の上にエイムオフセット)。 | |
AnimationNodeTimeScale |
Speed control. Make an animation play faster or slower at runtime. | 速度制御。実行時にアニメーションの再生速度を変更。 | |
AnimationNodeOneShot |
One-shot animation overlay. Perfect for attacks, emotes, hit reactions. | ワンショットアニメーションオーバーレイ。攻撃、エモート、被弾リアクションに最適。 | |
AnimationNodeTransition |
Switch between multiple inputs with crossfades. Alternative to state machines for simpler setups. | クロスフェード付きで複数の入力間を切り替え。シンプルなセットアップではステートマシンの代替。 |
9. OneShot Pattern (Attacks, Emotes)OneShotパターン(攻撃・エモート)
The OneShot node is one of the most useful patterns in AnimationTree. It plays a one-time animation on top of your base animation (like playing an attack swing while walking), then automatically returns to the base animation.
OneShotノードはAnimationTreeで最も有用なパターンの一つです。ベースアニメーションの上にワンタイムアニメーションを再生し(歩行中に攻撃スイングを再生するなど)、終了後に自動的にベースアニメーションに戻ります。
Setup in BlendTree
BlendTree内のセットアップ
To use OneShot, your AnimationTree root (or a state within it) needs to be a BlendTree:
OneShotを使うには、AnimationTreeのルート(またはその中の状態)がBlendTreeである必要があります:
# BlendTree graph setup:
#
# [StateMachine] ---> [OneShot "AttackOneShot"] ---> [Output]
# (base locomotion) ^
# |
# [Animation "Attack"]
# (shot input)
#
# The StateMachine provides the base (idle/walk/run).
# The Attack animation is connected to the OneShot's "shot" input.
Triggering from Code
コードからのトリガー
GDScriptextends CharacterBody2D
@onready var anim_tree: AnimationTree = $AnimationTree
func _input(event: InputEvent) -> void:
if event.is_action_pressed("attack"):
_play_attack()
func _play_attack() -> void:
# Fire the one-shot animation
anim_tree.set(
"parameters/AttackOneShot/request",
AnimationNodeOneShot.ONE_SHOT_REQUEST_FIRE
)
func _process(delta: float) -> void:
# Check if the one-shot is currently active
var is_attacking: bool = anim_tree.get("parameters/AttackOneShot/active")
if is_attacking:
# Optionally disable movement during attack
pass
OneShot Request Constants
OneShotリクエスト定数
| Constant | 定数 | Effect | 効果 |
|---|---|---|---|
ONE_SHOT_REQUEST_FIRE |
Start playing the one-shot animation | ワンショットアニメーションの再生開始 | |
ONE_SHOT_REQUEST_ABORT |
Cancel the one-shot and return to base immediately | ワンショットをキャンセルし即座にベースに戻る | |
ONE_SHOT_REQUEST_FADE_OUT |
Fade out the one-shot (uses fadeout_time property) | ワンショットをフェードアウト(fadeout_timeプロパティを使用) |
For combo systems, use multiple OneShot nodes in sequence or a nested state machine inside the OneShot's shot input with Attack1 → Attack2 → Attack3 states.
コンボシステムには、複数のOneShotノードを連続使用するか、OneShotのshot入力内にAttack1 → Attack2 → Attack3状態を持つネストされたステートマシンを使用します。
10. Practical Example: Full Character Controller実践例:完全なキャラクターコントローラー
Here is a complete 2D platformer character script that combines state machine locomotion with a OneShot attack. This is a production-ready pattern you can adapt to your own project.
ステートマシンによる移動とOneShot攻撃を組み合わせた、完全な2Dプラットフォーマーキャラクタースクリプトです。プロジェクトに合わせて応用できる実用的なパターンです。
GDScript — player.gdextends CharacterBody2D
const SPEED := 200.0
const JUMP_VELOCITY := -350.0
const SPRINT_MULTIPLIER := 1.6
@onready var anim_tree: AnimationTree = $AnimationTree
@onready var playback: AnimationNodeStateMachinePlayback = anim_tree.get("parameters/playback")
@onready var sprite: Sprite2D = $Sprite2D
var gravity: float = ProjectSettings.get_setting("physics/2d/default_gravity")
func _ready() -> void:
anim_tree.active = true
func _physics_process(delta: float) -> void:
_apply_gravity(delta)
_handle_jump()
_handle_movement()
move_and_slide()
_update_animation()
func _apply_gravity(delta: float) -> void:
if not is_on_floor():
velocity.y += gravity * delta
func _handle_jump() -> void:
if Input.is_action_just_pressed("jump") and is_on_floor():
velocity.y = JUMP_VELOCITY
func _handle_movement() -> void:
var direction := Input.get_axis("move_left", "move_right")
var is_sprinting := Input.is_action_pressed("sprint")
var current_speed := SPEED * (SPRINT_MULTIPLIER if is_sprinting else 1.0)
if direction != 0.0:
velocity.x = direction * current_speed
sprite.flip_h = direction < 0.0
else:
velocity.x = move_toward(velocity.x, 0.0, SPEED)
func _update_animation() -> void:
# Skip animation updates during attack
var is_attacking: bool = anim_tree.get("parameters/AttackOneShot/active")
if is_attacking:
return
if not is_on_floor():
if velocity.y < 0:
playback.travel("Jump")
else:
playback.travel("Fall")
elif abs(velocity.x) > 10.0:
if Input.is_action_pressed("sprint"):
playback.travel("Run")
else:
playback.travel("Walk")
else:
playback.travel("Idle")
func _input(event: InputEvent) -> void:
if event.is_action_pressed("attack") and is_on_floor():
anim_tree.set(
"parameters/AttackOneShot/request",
AnimationNodeOneShot.ONE_SHOT_REQUEST_FIRE
)
Root = BlendTree. Inside: a StateMachine node (with Idle/Walk/Run/Jump/Fall states) connected to a OneShot node ("AttackOneShot"), which connects to the Output. The attack animation connects to the OneShot's "shot" input.
Root = BlendTree。内部:StateMachineノード(Idle/Walk/Run/Jump/Fall状態)がOneShotノード("AttackOneShot")に接続され、Outputに接続。攻撃アニメーションはOneShotの"shot"入力に接続。
11. Troubleshootingトラブルシューティング
Check that active = true on the AnimationTree and that the anim_player property points to a valid AnimationPlayer. Also verify the AnimationPlayer actually has animations with the names you are referencing.
AnimationTreeのactive = trueを確認し、anim_playerプロパティが有効なAnimationPlayerを指していることを確認してください。参照しているアニメーション名がAnimationPlayerに実際に存在することも確認しましょう。
Ensure a valid transition path exists between the current state and the target state. travel() will silently fail if no path exists. Use state_machine.get_current_node() to debug what state you are actually in.
現在の状態とターゲット状態の間に有効なトランジションパスが存在することを確認してください。パスが存在しない場合、travel()は静かに失敗します。state_machine.get_current_node()で実際にどの状態にいるかデバッグしましょう。
Check that your blend_position value falls within the range of your blend space points. If your points are at 0.0 and 1.0, a value of 5.0 will not work as expected. Use clamp().
blend_positionの値がブレンドスペースのポイント範囲内にあることを確認してください。ポイントが0.0と1.0の場合、5.0の値は期待通りに機能しません。clamp()を使用してください。
Set active = true either in the editor (Inspector checkbox) or in your _ready() function. The AnimationTree does nothing until activated.
エディタ(インスペクターのチェックボックス)か_ready()関数でactive = trueを設定してください。AnimationTreeはアクティブ化するまで何も行いません。
Double-check that: (1) the transition's advance_mode is set to Auto, (2) the advance_condition name exactly matches what you set in code (case-sensitive), and (3) you are setting the parameter every frame in _physics_process().
以下を再確認してください:(1) トランジションのadvance_modeがAutoに設定されている、(2) advance_conditionの名前がコードで設定した名前と完全に一致する(大文字小文字を区別)、(3) _physics_process()で毎フレームパラメータを設定している。
AnimationTree handles animation playback only. Movement logic (velocity, move_and_slide()) is separate and must be implemented in your script's _physics_process().
AnimationTreeはアニメーション再生のみを処理します。移動ロジック(velocity、move_and_slide())は別であり、スクリプトの_physics_process()で実装する必要があります。
Want AI to Build Your AnimationTree?
AIにAnimationTreeを構築させたい?
Godot MCP Pro can create state machines, add states and transitions, configure blend trees, and set parameters — all from a single prompt. Tell your AI assistant what animation behavior you want, and it builds the entire AnimationTree for you.
Godot MCP Proはステートマシンの作成、状態とトランジションの追加、ブレンドツリーの設定、パラメータの設定を — 全て1つのプロンプトから実行できます。AIアシスタントに望むアニメーション動作を伝えるだけで、AnimationTree全体を構築します。
- create_animation_tree
- add_state_machine_state
- add_state_machine_transition
- set_blend_tree_node
- set_tree_parameter
- get_animation_tree_structure