animation_tree.rst 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408
  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. The ability to animate almost any property in any node or resource, as well as having dedicated transform, bezier,
  8. function calling, audio and sub-animation tracks, is pretty much unique.
  9. However, the support for blending those animations via ``AnimationPlayer`` is relatively limited, as only a fixed cross-fade transition time can be set.
  10. :ref:`AnimationTree <class_AnimationTree>` is a new node introduced in Godot 3.1 to deal with advanced transitions.
  11. It supersedes the ancient ``AnimationTreePlayer``, while adding a huge amount of features and flexibility.
  12. Creating an AnimationTree
  13. -------------------------
  14. Before starting, it must be made clear that an ``AnimationTree`` node does not contain its own animations.
  15. Instead, it uses animations contained in an ``AnimationPlayer`` node. This way, you can edit your animations (or import them from a 3D scene)
  16. as usual and then use this extra node to control the playback.
  17. The most common way to use ``AnimationTree`` is in a 3D scene. When importing your scenes from a 3D exchange format, they will usually come
  18. with animations built-in (either multiple ones or split from a large one on import).
  19. At the end, the imported Godot scene will contain the animations in a ``AnimationPlayer`` node.
  20. As 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://github.com/godotengine/tps-demo>`_, for reference:
  23. .. image:: img/animtree1.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. There are three main types of nodes that can be used in ``AnimationTree``:
  29. 1. Animation nodes, which reference an animation from the linked ``AnimationPlayer``.
  30. 2. Animation Root nodes, which are used to blend sub-nodes.
  31. 3. Animation Blend nodes, which are used within ``AnimationNodeBlendTree`` as single-graph blending via multiple input ports.
  32. To set a root node in ``AnimationTree``, a few types are available:
  33. .. image:: img/animtree2.png
  34. * ``AnimationNodeAnimation``: Selects an animation from the list and plays it. This is the simplest root node, and generally not used directly as root.
  35. * ``AnimationNodeBlendTree``: Contains many *blend* type nodes, such as mix, blend2, blend3, one shot, etc. This is one of the most commonly used roots.
  36. * ``AnimationNodeStateMachine``: Contains multiple root nodes as children in a graph. Each node is used as a *state*, and provides multiple functions to alternate between states.
  37. * ``AnimationNodeBlendSpace2D``: Allows placing root nodes in a 2D blend space. Control the blend position in 2D to mix between multiple animations.
  38. * ``AnimationNodeBlendSpace1D``: Simplified version of the above (1D).
  39. Blend tree
  40. ----------
  41. An ``AnimationNodeBlendTree`` can contain both root and regular nodes used for blending. Nodes are added to the graph from a menu:
  42. .. image:: img/animtree3.webp
  43. All blend trees contain an ``Output`` node by default, and something has to be connected to it in order for animations to play.
  44. The easiest way to test this functionality is to connect an ``Animation`` node to it directly:
  45. .. image:: img/animtree4.png
  46. This will simply play back the animation. Make sure that the ``AnimationTree`` is active for something to actually happen.
  47. Following is a short description of available nodes:
  48. Blend2 / Blend3
  49. ^^^^^^^^^^^^^^^
  50. These nodes will blend between two or three inputs by a user-specified blend value:
  51. .. image:: img/animtree5.gif
  52. For more complex blending, it is advised to use blend spaces instead.
  53. Blending can also use filters, i.e. you can control individually which tracks go through the blend function.
  54. This is very useful for layering animations on top of each other.
  55. .. image:: img/animtree6.png
  56. OneShot
  57. ^^^^^^^
  58. This node will execute a sub-animation and return once it finishes. Blend times for fading in and out can be customized, as well as filters.
  59. .. image:: img/animtree6b.gif
  60. After setting the request and changing the animation playback, the one-shot node automatically clears the request on the next process frame by setting its ``request`` value to ``AnimationNodeOneShot.ONE_SHOT_REQUEST_NONE``.
  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 as above).
  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 as above).
  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 as above).
  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 can be used to cause a seek command to happen to any sub-children of the animation graph. Use this node type to play an ``Animation`` from the start or a certain playback position inside the ``AnimationNodeBlendTree``.
  85. After setting the time and changing the animation playback, the seek node automatically goes into sleep mode on the next process frame by setting its ``seek_request`` value to ``-1.0``.
  86. .. tabs::
  87. .. code-tab:: gdscript GDScript
  88. # Play child animation from the start.
  89. animation_tree.set("parameters/TimeSeek/seek_request", 0.0)
  90. # Alternative syntax (same result as above).
  91. animation_tree["parameters/TimeSeek/seek_request"] = 0.0
  92. # Play child animation from 12 second timestamp.
  93. animation_tree.set("parameters/TimeSeek/seek_request", 12.0)
  94. # Alternative syntax (same result as above).
  95. animation_tree["parameters/TimeSeek/seek_request"] = 12.0
  96. .. code-tab:: csharp
  97. // Play child animation from the start.
  98. animationTree.Set("parameters/TimeSeek/seek_request", 0.0);
  99. // Play child animation from 12 second timestamp.
  100. animationTree.Set("parameters/TimeSeek/seek_request", 12.0);
  101. TimeScale
  102. ^^^^^^^^^
  103. Allows scaling the speed of the animation (or reverse it) connected to the `in` input via the `scale` parameter. Setting the `scale` to 0 will pause the animation.
  104. Transition
  105. ^^^^^^^^^^
  106. Very simple state machine (when you don't want to cope with a ``StateMachine`` node). Animations can be connected to the outputs and transition times can be specified.
  107. After setting the request and changing the animation playback, the transition node automatically clears the request on the next process frame by setting its ``transition_request`` value to an empty string (``""``).
  108. .. tabs::
  109. .. code-tab:: gdscript GDScript
  110. # Play child animation connected to "state_2" port.
  111. animation_tree.set("parameters/Transition/transition_request", "state_2")
  112. # Alternative syntax (same result as above).
  113. animation_tree["parameters/Transition/transition_request"] = "state_2"
  114. # Get current state name (read-only).
  115. animation_tree.get("parameters/Transition/current_state")
  116. # Alternative syntax (same result as above).
  117. animation_tree["parameters/Transition/current_state"]
  118. # Get current state index (read-only).
  119. animation_tree.get("parameters/Transition/current_index"))
  120. # Alternative syntax (same result as above).
  121. animation_tree["parameters/Transition/current_index"]
  122. .. code-tab:: csharp
  123. // Play child animation connected to "state_2" port.
  124. animationTree.Set("parameters/Transition/transition_request", "state_2");
  125. // Get current state name (read-only).
  126. animationTree.Get("parameters/Transition/current_state");
  127. // Get current state index (read-only).
  128. animationTree.Get("parameters/Transition/current_index");
  129. BlendSpace2D
  130. ^^^^^^^^^^^^
  131. ``BlendSpace2D`` is a node to do advanced blending in two dimensions. Points are added to a two-dimensional space and then a position
  132. can be controlled to determine blending:
  133. .. image:: img/animtree7.gif
  134. The ranges in X and Y can be controlled (and labeled for convenience). By default, points can be placed anywhere (right-click on
  135. the coordinate system or use the *add point* button) and triangles will be generated automatically using Delaunay.
  136. .. image:: img/animtree8.gif
  137. It is also possible to draw the triangles manually by disabling the *auto triangle* option, though this is rarely necessary:
  138. .. image:: img/animtree9.png
  139. Finally, it is possible to change the blend mode. By default, blending happens by interpolating points inside the closest triangle.
  140. When dealing with 2D animations (frame by frame), you may want to switch to *Discrete* mode.
  141. Alternatively, if you want to keep the current play position when switching between discrete animations, there is a *Carry* mode.
  142. This mode can be changed in the *Blend* menu:
  143. .. image:: img/animtree10.png
  144. BlendSpace1D
  145. ^^^^^^^^^^^^
  146. This is similar to 2D blend spaces, but in one dimension (so triangles are not needed).
  147. StateMachine
  148. ^^^^^^^^^^^^
  149. This node acts as a state machine with root nodes as states. Root nodes can be created and connected via lines. States are connected via *Transitions*,
  150. which are connections with special properties. Transitions are uni-directional, but two can be used to connect in both directions.
  151. .. image:: img/animtree11.gif
  152. There are many types of transition:
  153. .. image:: img/animtree12.png
  154. * *Immediate*: Will switch to the next state immediately. The current state will end and blend into the beginning of the new one.
  155. * *Sync*: Will switch to the next state immediately, but will seek the new state to the playback position of the old state.
  156. * *At End*: Will wait for the current state playback to end, then switch to the beginning of the next state animation.
  157. Transitions also have a few properties. Click any transition and it will be displayed in the inspector dock:
  158. .. image:: img/animtree13.png
  159. * *Switch Mode* is the transition type (see above), it can be modified after creation here.
  160. * *Auto Advance* will turn on the transition automatically when this state is reached. This works best with the *At End* switch mode.
  161. * *Advance Condition* will turn on auto advance when this condition is set. This is a custom text field that can be filled with a variable name.
  162. The variable can be modified from code (more on this later).
  163. * *Xfade Time* is the time to cross-fade between this state and the next.
  164. * *Priority* is used together with the ``travel()`` function from code (more on this later). Lower priority transitions are preferred when travelling through the tree.
  165. * *Disabled* toggles disabling this transition (when disabled, it will not be used during travel or auto advance).
  166. For better blending
  167. -------------------
  168. In Godot 4.0+, in order for the blending results to be deterministic (reproducible and always consistent),
  169. the blended property values must have a specific initial value.
  170. For example, in the case of two animations to be blended, if one animation has a property track and the other does not,
  171. the blended animation is calculated as if the latter animation had a property track with the initial value.
  172. When using Position/Rotation/Scale 3D tracks for Skeleton3D bones, the initial value is Bone Rest.
  173. For other properties, the initial value is ``0`` and if the track is present in the ``RESET`` animation,
  174. the value of its first keyframe is used instead.
  175. For example, the following AnimationPlayer has two animations, but one of them lacks a Property track for Position.
  176. .. image:: img/blending1.webp
  177. This means that the animation lacking that will treat those Positions as ``Vector2(0, 0)``.
  178. .. image:: img/blending2.webp
  179. This problem can be solved by adding a Property track for Position as an initial value to the ``RESET`` animation.
  180. .. image:: img/blending3.webp
  181. .. image:: img/blending4.webp
  182. .. note:: Be aware that the ``RESET`` animation exists to define the default pose when loading an object originally.
  183. It is assumed to have only one frame and is not expected to be played back using the timeline.
  184. Also keep in mind that the Rotation 3D tracks and the Property tracks for 2D rotation
  185. with Interpolation Type set to Linear Angle or Cubic Angle will prevent rotation of more than 180 degrees
  186. from the initial value as blended animation.
  187. This can be useful for Skeleton3Ds to prevent the bones penetrating the body when blending animations.
  188. Therefore, Skeleton3D's Bone Rest values should be as close to the midpoint of the movable range as possible.
  189. **This means that for humanoid models, it is preferable to import them in a T-pose**.
  190. .. image:: img/blending5.webp
  191. You can see that the shortest rotation path from Bone Rests is prioritized rather than the shortest rotation path between animations.
  192. If you need to rotate Skeleton3D itself more than 180 degrees by blend animations for movement, you can use Root Motion.
  193. Root motion
  194. -----------
  195. 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.
  196. This allows animating characters in a way where steps actually match the floor below. It also allows precise interaction with objects during cinematics.
  197. 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
  198. transformation visually (the animation will stay in place).
  199. .. image:: img/animtree14.png
  200. Afterwards, the actual motion can be retrieved via the :ref:`AnimationTree <class_AnimationTree>` API as a transform:
  201. .. tabs::
  202. .. code-tab:: gdscript GDScript
  203. # Get the motion delta.
  204. animation_tree.get_root_motion_position()
  205. animation_tree.get_root_motion_rotation()
  206. animation_tree.get_root_motion_scale()
  207. # Get the actual blended value of the animation.
  208. animation_tree.get_root_motion_position_accumulator()
  209. animation_tree.get_root_motion_rotation_accumulator()
  210. animation_tree.get_root_motion_scale_accumulator()
  211. .. code-tab:: csharp
  212. // Get the motion delta.
  213. animationTree.GetRootMotionPosition();
  214. animationTree.GetRootMotionRotation();
  215. animationTree.GetRootMotionScale();
  216. // Get the actual blended value of the animation.
  217. animationTree.GetRootMotionPositionAccumulator();
  218. animationTree.GetRootMotionRotationAccumulator();
  219. animationTree.GetRootMotionScaleAccumulator();
  220. This can be fed to functions such as :ref:`CharacterBody3D.move_and_slide <class_CharacterBody3D_method_move_and_slide>` to control the character movement.
  221. There is also a tool node, ``RootMotionView``, that can be placed in a scene and will act as a custom floor for your
  222. character and animations (this node is disabled by default during the game).
  223. .. image:: img/animtree15.gif
  224. Controlling from code
  225. ---------------------
  226. After building the tree and previewing it, the only question remaining is "How is all this controlled from code?".
  227. Keep in mind that the animation nodes are just resources and, as such, they are shared between all instances using them.
  228. Setting values in the nodes directly will affect all instances of the scene that uses this ``AnimationTree``.
  229. This is generally undesirable, but does have some cool use cases, e.g. you can copy and paste parts of your animation tree,
  230. or reuse nodes with a complex layout (such as a state machine or blend space) in different animation trees.
  231. The actual animation data is contained in the ``AnimationTree`` node and is accessed via properties.
  232. Check the "Parameters" section of the ``AnimationTree`` node to see all the parameters that can be modified in real-time:
  233. .. image:: img/animtree16.png
  234. This is handy because it makes it possible to animate them from an ``AnimationPlayer``, or even the ``AnimationTree`` itself,
  235. allowing the realization of very complex animation logic.
  236. To modify these values from code, the property path must be obtained. This is done easily by hovering the mouse over any of the parameters:
  237. .. image:: img/animtree17.png
  238. Which allows setting them or reading them:
  239. .. tabs::
  240. .. code-tab:: gdscript GDScript
  241. animation_tree.set("parameters/eye_blend/blend_amount", 1.0)
  242. # Simpler alternative form:
  243. animation_tree["parameters/eye_blend/blend_amount"] = 1.0
  244. .. code-tab:: csharp
  245. animationTree.Set("parameters/eye_blend/blend_amount", 1.0);
  246. State machine travel
  247. --------------------
  248. One of the nice features in Godot's ``StateMachine`` implementation is the ability to travel. The graph can be instructed to go from the
  249. current state to another one, while visiting all the intermediate ones. This is done via the A\* algorithm.
  250. 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.
  251. To use the travel ability, you should first retrieve the :ref:`AnimationNodeStateMachinePlayback <class_AnimationNodeStateMachinePlayback>`
  252. object from the ``AnimationTree`` node (it is exported as a property).
  253. .. tabs::
  254. .. code-tab:: gdscript GDScript
  255. var state_machine = animation_tree["parameters/playback"]
  256. .. code-tab:: csharp
  257. AnimationNodeStateMachinePlayback stateMachine = (AnimationNodeStateMachinePlayback)animationTree.Get("parameters/playback");
  258. Once retrieved, it can be used by calling one of the many functions it offers:
  259. .. tabs::
  260. .. code-tab:: gdscript GDScript
  261. state_machine.travel("SomeState")
  262. .. code-tab:: csharp
  263. stateMachine.Travel("SomeState");
  264. The state machine must be running before you can travel. Make sure to either call ``start()`` or choose a node to **Autoplay on Load**.
  265. .. image:: img/animtree18.png