2
0

animation_tree.rst 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451
  1. .. _doc_animation_tree:
  2. Using AnimationTree
  3. ===================
  4. Introduction
  5. ------------
  6. With :ref:`AnimationPlayer <class_AnimationPlayer>`, Godot has one of the most flexible animation systems that you can find in any game engine.
  7. It is pretty much unique in its ability to animate almost any property in any node or resource, and its dedicated transform, bezier,
  8. function calling, audio, and sub-animation tracks.
  9. However, the support for blending those animations via ``AnimationPlayer`` is limited, as you can only set a fixed cross-fade transition time.
  10. :ref:`AnimationTree <class_AnimationTree>` is a new node introduced in Godot 3.1 to deal with advanced transitions.
  11. It replaces the ancient ``AnimationTreePlayer``, while adding a huge amount of features and flexibility.
  12. AnimationTree and AnimationPlayer
  13. ---------------------------------
  14. Before starting, know that an ``AnimationTree`` node does not contain its own animations.
  15. Instead, it uses animations contained in an ``AnimationPlayer`` node. You create, edit, or import your animations in an ``AnimationPlayer``
  16. and then use an ``AnimationTree`` to control the playback.
  17. ``AnimationPlayer`` and ``AnimationTree`` can be used in both 2D and 3D scenes. When importing 3D scenes and their animations, you can use
  18. `name suffixes <https://docs.godotengine.org/en/stable/tutorials/assets_pipeline/importing_3d_scenes/node_type_customization.html#animation-loop-loop-cycle>`_
  19. to simplify the process and import with the correct properties. At the end, the imported Godot scene will contain the animations in an ``AnimationPlayer`` node.
  20. Since you rarely use imported scenes directly in Godot (they are either instantiated or inherited from), you can place the ``AnimationTree`` node in your
  21. new scene which contains the imported one. Afterwards, point the ``AnimationTree`` node to the ``AnimationPlayer`` that was created in the imported scene.
  22. This is how it's done in the `Third Person Shooter demo <https://godotengine.org/asset-library/asset/678>`_, for reference:
  23. .. image:: img/animtree_treeandplayersetup.png
  24. A new scene was created for the player with a ``CharacterBody3D`` as root. Inside this scene, the original ``.dae`` (Collada) file was instantiated
  25. and an ``AnimationTree`` node was created.
  26. Creating a tree
  27. ---------------
  28. To use an ``AnimationTree``, you have to set a root node. An animation root node is a class that contains and evaluates sub-nodes and outputs an animation.
  29. There are 3 types of sub-nodes:
  30. 1. Animation nodes, which reference an animation from the linked ``AnimationPlayer``.
  31. 2. Animation Root nodes, which are used to blend sub-nodes and can be nested.
  32. 3. Animation Blend nodes, which are used in an ``AnimationNodeBlendTree``, a 2D graph of nodes. Blend nodes take multiple input ports and give one output port.
  33. A few types of root nodes are available:
  34. .. image:: img/animtree_rootnodes.png
  35. * ``AnimationNodeAnimation``: Selects an animation from the list and plays it. This is the simplest root node, and generally not used as a root.
  36. * ``AnimationNodeBlendTree``: Contains multiple nodes as children in a graph. Many blend nodes are available, such as mix, blend2, blend3, one shot, etc.
  37. * ``AnimationNodeBlendSpace1D``: Allows linear blending between two animation nodes. Control the blend position in a 1D blend space to mix between animations.
  38. * ``AnimationNodeBlendSpace2D``: Allows linear blending between three animation nodes. Control the blend position in a 2D blend space to mix between animations.
  39. * ``AnimationNodeStateMachine``: Contains multiple nodes as children in a graph. Each node is used as a state, with multiple functions used to alternate between states.
  40. Blend tree
  41. ----------
  42. When you make an ``AnimationNodeBlendTree``, you get an empty 2d graph in the bottom panel, under the AnimationTree tab. It contains only an ``Output``
  43. node by default.
  44. .. image:: img/animtree_emptyblendtree.webp
  45. In order for animations to play, a node has to be connected to to the output. You can add nodes from the **Add Node..** menu or by right clicking an empty space:
  46. .. image:: img/animtree_blendnodes.webp
  47. The simplest connection to make is to connect an ``Animation`` node to the output directly, which will just play back the animation.
  48. .. image:: img/animtree_animtooutput.png
  49. Following is a description of the other available nodes:
  50. Blend2 / Blend3
  51. ~~~~~~~~~~~~~~~
  52. These nodes will blend between two or three inputs by a user-specified blend value:
  53. .. image:: img/animtree_blend2.gif
  54. Blending can use **filters** to control individually which tracks get blended and which do not. This can be useful for layering animations on top of each other.
  55. .. image:: img/animtree_filtering.png
  56. For more complex blending, it is recommended to use blend spaces instead.
  57. OneShot
  58. ~~~~~~~
  59. This node will execute an animation once and return when it finishes. You can customize blend times for fading in and out, as well as filters.
  60. .. image:: img/animtree_oneshot.gif
  61. .. tabs::
  62. .. code-tab:: gdscript GDScript
  63. # Play child animation connected to "shot" port.
  64. animation_tree.set("parameters/OneShot/request", AnimationNodeOneShot.ONE_SHOT_REQUEST_FIRE)
  65. # Alternative syntax (same result).
  66. animation_tree["parameters/OneShot/request"] = AnimationNodeOneShot.ONE_SHOT_REQUEST_FIRE
  67. # Abort child animation connected to "shot" port.
  68. animation_tree.set("parameters/OneShot/request", AnimationNodeOneShot.ONE_SHOT_REQUEST_ABORT)
  69. # Alternative syntax (same result).
  70. animation_tree["parameters/OneShot/request"] = AnimationNodeOneShot.ONE_SHOT_REQUEST_ABORT
  71. # Get current state (read-only).
  72. animation_tree.get("parameters/OneShot/active"))
  73. # Alternative syntax (same result).
  74. animation_tree["parameters/OneShot/active"]
  75. .. code-tab:: csharp
  76. // Play child animation connected to "shot" port.
  77. animationTree.Set("parameters/OneShot/request", (int)AnimationNodeOneShot.OneShotRequest.Fire);
  78. // Abort child animation connected to "shot" port.
  79. animationTree.Set("parameters/OneShot/request", (int)AnimationNodeOneShot.OneShotRequest.Abort);
  80. // Get current state (read-only).
  81. animationTree.Get("parameters/OneShot/active");
  82. TimeSeek
  83. ~~~~~~~~
  84. This node allows you to seek to a time in the animation connected to its `in` input. Use this node to play an ``Animation`` starting from a certain playback position.
  85. Note that the seek request value is measured in seconds, so if you would like to play an animation from the beginning, set the value to ``0.0``, or if you would like
  86. to play an animation from 3 seconds in, set the value to ``3.0``.
  87. .. image:: img/animtree_timeseek.webp
  88. .. tabs::
  89. .. code-tab:: gdscript GDScript
  90. # Play child animation from the start.
  91. animation_tree.set("parameters/TimeSeek/seek_request", 0.0)
  92. # Alternative syntax (same result).
  93. animation_tree["parameters/TimeSeek/seek_request"] = 0.0
  94. # Play child animation from 12 second timestamp.
  95. animation_tree.set("parameters/TimeSeek/seek_request", 12.0)
  96. # Alternative syntax (same result).
  97. animation_tree["parameters/TimeSeek/seek_request"] = 12.0
  98. .. code-tab:: csharp
  99. // Play child animation from the start.
  100. animationTree.Set("parameters/TimeSeek/seek_request", 0.0);
  101. // Play child animation from 12 second timestamp.
  102. animationTree.Set("parameters/TimeSeek/seek_request", 12.0);
  103. TimeScale
  104. ~~~~~~~~~
  105. This node allows you to scale the speed of the animation connected to its `in` input. The speed of the animation will be multiplied by the number in the `scale`
  106. parameter. Setting the scale to 0 will pause the animation. Setting the scale to a negative number will play the animation backwards.
  107. .. image:: img/animtree_timescale.webp
  108. Transition
  109. ~~~~~~~~~~
  110. This node is a simplified version of a StateMachine. You connect animations to the inputs, and the current state index determines which animation to play.
  111. You may specify a crossfade transition time. In the Inspector, you may change the number of input ports, rearrange inputs, or delete inputs.
  112. .. image:: img/animtree_transition.webp
  113. .. tabs::
  114. .. code-tab:: gdscript GDScript
  115. # Play child animation connected to "state_2" port.
  116. animation_tree.set("parameters/Transition/transition_request", "state_2")
  117. # Alternative syntax (same result).
  118. animation_tree["parameters/Transition/transition_request"] = "state_2"
  119. # Get current state name (read-only).
  120. animation_tree.get("parameters/Transition/current_state")
  121. # Alternative syntax (same result).
  122. animation_tree["parameters/Transition/current_state"]
  123. # Get current state index (read-only).
  124. animation_tree.get("parameters/Transition/current_index"))
  125. # Alternative syntax (same result).
  126. animation_tree["parameters/Transition/current_index"]
  127. .. code-tab:: csharp
  128. // Play child animation connected to "state_2" port.
  129. animationTree.Set("parameters/Transition/transition_request", "state_2");
  130. // Get current state name (read-only).
  131. animationTree.Get("parameters/Transition/current_state");
  132. // Get current state index (read-only).
  133. animationTree.Get("parameters/Transition/current_index");
  134. StateMachine
  135. ~~~~~~~~~~~~
  136. When you make an ``AnimationNodeStateMachine``, you get an empty 2d graph in the bottom panel, under the AnimationTree tab. It contains a ``Start`` and ``End``
  137. state by default.
  138. .. image:: img/animtree_emptystatemachine.webp
  139. To add states, right click or use the **create new nodes** button, whose icon is a plus in a box. You can add animations, blendspaces, blendtrees, or even
  140. another StateMachine. To edit one of these more complex sub-nodes, click on the pencil icon on the right of the state. To return to the original StateMachine,
  141. click **Root** on the top left of the panel.
  142. Before the StateMachine can do anything useful, the states must be connected with transitions. To add a transition, click the **connect nodes** button, which is
  143. a line with a right-facing arrow, and drag between two states. You can create 2 transitions between states, one going in each direction.
  144. .. image:: img/animtree_connections.gif
  145. There are 3 types of transitions:
  146. .. image:: img/animtree_transitiontypes.png
  147. * *Immediate*: Will switch to the next state immediately.
  148. * *Sync*: Will switch to the next state immediately, but will seek the new state to the playback position of the old state.
  149. * *At End*: Will wait for the current state playback to end, then switch to the beginning of the next state animation.
  150. Transitions also have a few properties. Click a transition and it will be displayed in the inspector:
  151. .. image:: img/animtree_statemachinetransitionproperties.webp
  152. * *Xfade Time* is the time to cross-fade between this state and the next.
  153. * *Xfade Curve* is a cross-fade following a curve rather than a linear blend.
  154. * *Reset* determines whether the state you are switching into plays from the beginning (true) or not (false).
  155. * *Priority* is used together with the ``travel()`` function from code (more on this later). Lower priority transitions are preferred when travelling through the tree.
  156. * *Switch Mode* is the transition type (see above). It can be changed after creation here.
  157. * *Advance Mode* determines the advance mode. If ``Disabled``, the transition will not be used. If ``Enabled``, the transition will only be used during ``travel()``. If ``Auto``, the transition will be used if the advance condition and expression are true, or if there are no advance conditions/expressions.
  158. Advance Condition and Advance Expression
  159. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  160. The last 2 properties in a StateMachine transition are ``Advance Condition`` and ``Advance Expression.`` When the Advance Mode is set to *Auto*, these
  161. determine if the transition will advance or not.
  162. Advance Condition is a true/false check. You may put a custom variable name in the text field, and when the StateMachine reaches this transition,
  163. it will check if your variable is *true*. If so, the transition continues. Note that the advance condition **only** checks if a variable is *true*,
  164. and it cannot check for falseness.
  165. This gives the Advance Condition a very limited capability. If you wanted to make a transition back and forth based on one property, you would need to make
  166. 2 variables that have opposite values, and check if either of them are true. This is why, in Godot 4, the Advance Expression was added.
  167. The Advance Expression works similar to the Advance Condition, but instead of checking if one variable is true, it evaluates any expression. An expression
  168. is anything you could put in an ``if`` statement. These are all examples of expressions that would work in the Advance Expression:
  169. * ``is_walking``
  170. * ``is_walking`` == true
  171. * ``is_walking && !is_idle``
  172. * ``velocity > 0``
  173. * ``player.is_on_floor()``
  174. Here is an example of an improperly-set-up StateMachine transition using Advance Condition:
  175. .. image:: img/animtree_badanimcondition.webp
  176. .. image:: img/animtree_badanimcondition.gif
  177. This is not working because there is a ``!`` variable in the Advance Condition, which cannot be checked.
  178. Here is the same example, set up properly, using two opposite variables:
  179. .. image:: img/animtree_goodanimcondition.webp
  180. .. image:: img/animtree_goodanimcondition.gif
  181. Here is the same example, but using Advance Expression rather than Advance Condition, which eliminates the need for two variables:
  182. .. image:: img/animtree_goodanimexpression.webp
  183. .. image:: img/animtree_goodanimexpression2.webp
  184. .. image:: img/animtree_goodanimexpression.gif
  185. In order to use Advance Expressions, the Advance Expression Base Node has to be set from the Inspector of the AnimationTree node. By default, it is set
  186. to the AnimationTree node itself, but it needs to point to whatever node contains the script with your animation variables.
  187. StateMachine travel
  188. ^^^^^^^^^^^^^^^^^^^
  189. One of the nice features in Godot's ``StateMachine`` implementation is the ability to travel. You can instruct the graph to go from the
  190. current state to another one, while visiting all the intermediate ones. This is done via the A\* algorithm.
  191. If there is no path of transitions starting at the current state and finishing at the destination state, the graph teleports to the destination state.
  192. To use the travel ability, you should first retrieve the :ref:`AnimationNodeStateMachinePlayback <class_AnimationNodeStateMachinePlayback>`
  193. object from the ``AnimationTree`` node (it is exported as a property), and then call one of its many functions:
  194. .. tabs::
  195. .. code-tab:: gdscript GDScript
  196. var state_machine = animation_tree["parameters/playback"]
  197. state_machine.travel("SomeState")
  198. .. code-tab:: csharp
  199. AnimationNodeStateMachinePlayback stateMachine = (AnimationNodeStateMachinePlayback)animationTree.Get("parameters/playback");
  200. stateMachine.Travel("SomeState");
  201. The StateMachine must be running before you can travel. Make sure to either call ``start()`` or connect a node to **Start**.
  202. BlendSpace2D and BlendSpace1D
  203. -----------------------------
  204. ``BlendSpace2D`` is a node to do advanced blending in two dimensions. Points representing animations are added to a 2D space and then a position between them
  205. is controlled to determine the blending:
  206. .. image:: img/animtree_blendspace2d.gif
  207. You may place these points anywhere on the graph by right clicking or using the **add point** button, whose icon is a pen and point.
  208. Wherever you place the points, the triangle between them will be generated automatically using Delaunay.
  209. You may also control and label the ranges in X and Y.
  210. .. image:: img/animtree_blendspacepoints.gif
  211. Finally, you may also change the blend mode. By default, blending happens by interpolating points inside the closest triangle. When dealing with 2D
  212. animations (frame by frame), you may want to switch to *Discrete* mode. Alternatively, if you want to keep the current play position when switching
  213. between discrete animations, there is a *Carry* mode. This mode can be changed in the *Blend* menu:
  214. .. image:: img/animtree_blendmode.png
  215. BlendSpace1D works just like BlendSpace2D, but in one dimension (a line). Triangles are not used.
  216. .. image:: img/animtree_blendspace1d.webp
  217. For better blending
  218. -------------------
  219. In Godot 4.0+, in order for the blending results to be deterministic (reproducible and always consistent),
  220. the blended property values must have a specific initial value.
  221. For example, in the case of two animations to be blended, if one animation has a property track and the other does not,
  222. the blended animation is calculated as if the latter animation had a property track with the initial value.
  223. When using Position/Rotation/Scale 3D tracks for Skeleton3D bones, the initial value is Bone Rest.
  224. For other properties, the initial value is ``0`` and if the track is present in the ``RESET`` animation,
  225. the value of its first keyframe is used instead.
  226. For example, the following AnimationPlayer has two animations, but one of them lacks a Property track for Position.
  227. .. image:: img/blending1.webp
  228. This means that the animation lacking that will treat those Positions as ``Vector2(0, 0)``.
  229. .. image:: img/blending2.webp
  230. This problem can be solved by adding a Property track for Position as an initial value to the ``RESET`` animation.
  231. .. image:: img/blending3.webp
  232. .. image:: img/blending4.webp
  233. .. note:: Be aware that the ``RESET`` animation exists to define the default pose when loading an object originally.
  234. It is assumed to have only one frame and is not expected to be played back using the timeline.
  235. Also keep in mind that the Rotation 3D tracks and the Property tracks for 2D rotation
  236. with Interpolation Type set to Linear Angle or Cubic Angle will prevent rotations greater than 180 degrees
  237. from the initial value as blended animation.
  238. This can be useful for Skeleton3Ds to prevent the bones penetrating the body when blending animations.
  239. Therefore, Skeleton3D's Bone Rest values should be as close to the midpoint of the movable range as possible.
  240. **This means that for humanoid models, it is preferable to import them in a T-pose**.
  241. .. image:: img/blending5.webp
  242. You can see that the shortest rotation path from Bone Rests is prioritized rather than the shortest rotation path between animations.
  243. If you need to rotate Skeleton3D itself more than 180 degrees by blend animations for movement, you can use Root Motion.
  244. Root motion
  245. -----------
  246. When working with 3D animations, a popular technique is for animators to use the root skeleton bone to give motion to the rest of the skeleton.
  247. This allows animating characters in a way where steps actually match the floor below. It also allows precise interaction with objects during cinematics.
  248. When playing back the animation in Godot, it is possible to select this bone as the *root motion track*. Doing so will cancel the bone
  249. transformation visually (the animation will stay in place).
  250. .. image:: img/animtree_rootmotiontrack.webp
  251. Afterwards, the actual motion can be retrieved via the :ref:`AnimationTree <class_AnimationTree>` API as a transform:
  252. .. tabs::
  253. .. code-tab:: gdscript GDScript
  254. # Get the motion delta.
  255. animation_tree.get_root_motion_position()
  256. animation_tree.get_root_motion_rotation()
  257. animation_tree.get_root_motion_scale()
  258. # Get the actual blended value of the animation.
  259. animation_tree.get_root_motion_position_accumulator()
  260. animation_tree.get_root_motion_rotation_accumulator()
  261. animation_tree.get_root_motion_scale_accumulator()
  262. .. code-tab:: csharp
  263. // Get the motion delta.
  264. animationTree.GetRootMotionPosition();
  265. animationTree.GetRootMotionRotation();
  266. animationTree.GetRootMotionScale();
  267. // Get the actual blended value of the animation.
  268. animationTree.GetRootMotionPositionAccumulator();
  269. animationTree.GetRootMotionRotationAccumulator();
  270. animationTree.GetRootMotionScaleAccumulator();
  271. This can be fed to functions such as :ref:`CharacterBody3D.move_and_slide <class_CharacterBody3D_method_move_and_slide>` to control the character movement.
  272. There is also a tool node, ``RootMotionView``, you can place a scene that will act as a custom floor for your
  273. character and animations (this node is disabled by default during the game).
  274. .. image:: img/animtree15.gif
  275. Controlling from code
  276. ---------------------
  277. After building the tree and previewing it, the only question remaining is "How is all this controlled from code?".
  278. Keep in mind that the animation nodes are just resources, so they are shared between all instances using them.
  279. Setting values in the nodes directly will affect all instances of the scene that uses this ``AnimationTree``.
  280. This is generally undesirable, but does have some cool use cases, e.g. you can copy and paste parts of your animation tree,
  281. or reuse nodes with a complex layout (such as a StateMachine or blend space) in different animation trees.
  282. The actual animation data is contained in the ``AnimationTree`` node and is accessed via properties.
  283. Check the "Parameters" section of the ``AnimationTree`` node to see all the parameters that can be modified in real-time:
  284. .. image:: img/animtree_parameters.webp
  285. This is handy because it makes it possible to animate them from an ``AnimationPlayer``, or even the ``AnimationTree`` itself,
  286. allowing very complex animation logic.
  287. To modify these values from code, you must obtain the property path. You can find them by hovering your mouse over any of the parameters:
  288. .. image:: img/animtree_propertypath.webp
  289. Then you can set or read them:
  290. .. tabs::
  291. .. code-tab:: gdscript GDScript
  292. animation_tree.set("parameters/eye_blend/blend_amount", 1.0)
  293. # Alternate syntax (same result)
  294. animation_tree["parameters/eye_blend/blend_amount"] = 1.0
  295. .. code-tab:: csharp
  296. animationTree.Set("parameters/eye_blend/blend_amount", 1.0);
  297. .. note:: Advance Expressions from a StateMachine will not be found under the parameters. This is because they are held in another script rather than the
  298. AnimationTree itself. Advance `Conditions` will be found under parameters.