09.adding_animations.rst 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634
  1. :article_outdated: True
  2. .. _doc_first_3d_game_character_animation:
  3. Character animation
  4. ===================
  5. In this final lesson, we'll use Godot's built-in animation tools to make our
  6. characters float and flap. You'll learn to design animations in the editor and
  7. use code to make your game feel alive.
  8. |image0|
  9. We'll start with an introduction to using the animation editor.
  10. Using the animation editor
  11. --------------------------
  12. The engine comes with tools to author animations in the editor. You can then use
  13. the code to play and control them at runtime.
  14. Open the player scene, select the ``Player`` node, and add an :ref:`AnimationPlayer <class_AnimationPlayer>` node.
  15. The *Animation* dock appears in the bottom panel.
  16. |image1|
  17. It features a toolbar and the animation drop-down menu at the top, a track
  18. editor in the middle that's currently empty, and filter, snap, and zoom options
  19. at the bottom.
  20. Let's create an animation. Click on *Animation -> New*.
  21. |image2|
  22. Name the animation "float".
  23. |image3|
  24. Once you've created the animation, the timeline appears with numbers representing
  25. time in seconds.
  26. |image4|
  27. We want the animation to start playback automatically at the start of the game.
  28. Also, it should loop.
  29. To do so, you can click the button with an "A+" icon in the animation toolbar
  30. and the looping arrows, respectively.
  31. |image5|
  32. You can also pin the animation editor by clicking the pin icon in the top-right.
  33. This prevents it from folding when you click on the viewport and deselect the
  34. nodes.
  35. |image6|
  36. Set the animation duration to ``1.2`` seconds in the top-right of the dock.
  37. |image7|
  38. You should see the gray ribbon widen a bit. It shows you the start and end of
  39. your animation and the vertical blue line is your time cursor.
  40. |image8|
  41. You can click and drag the slider in the bottom-right to zoom in and out of the
  42. timeline.
  43. |image9|
  44. The float animation
  45. -------------------
  46. With the animation player node, you can animate most properties on as many nodes
  47. as you need. Notice the key icon next to properties in the *Inspector*. You can
  48. click any of them to create a keyframe, a time and value pair for the
  49. corresponding property. The keyframe gets inserted where your time cursor is in
  50. the timeline.
  51. Let's insert our first keys. Here, we will animate both the position and the
  52. rotation of the ``Character`` node.
  53. Select the ``Character`` and in the *Inspector* expand the *Transform* section. Click the key icon next to *Position*, and *Rotation*.
  54. |image10|
  55. .. image:: img/09.adding_animations/curves.webp
  56. For this tutorial, just create RESET Track(s) which is the default choice
  57. Two tracks appear in the editor with a diamond icon representing each keyframe.
  58. |image11|
  59. You can click and drag on the diamonds to move them in time. Move the
  60. position key to ``0.3`` seconds and the rotation key to ``0.1`` seconds.
  61. |image12|
  62. Move the time cursor to ``0.5`` seconds by clicking and dragging on the gray
  63. timeline.
  64. |timeline_05_click|
  65. In the *Inspector*, set the *Position*'s *Y* axis to ``0.65`` meters and the *Rotation*' *X* axis to ``8``.
  66. |image13|
  67. Create a keyframe for both properties
  68. |second_keys_both|
  69. Now, move the position keyframe to ``0.7``
  70. seconds by dragging it on the timeline.
  71. |image14|
  72. .. note::
  73. A lecture on the principles of animation is beyond the scope of this
  74. tutorial. Just note that you don't want to time and space everything evenly.
  75. Instead, animators play with timing and spacing, two core animation
  76. principles. You want to offset and contrast in your character's motion to
  77. make them feel alive.
  78. Move the time cursor to the end of the animation, at ``1.2`` seconds. Set the Y
  79. position to about ``0.35`` and the X rotation to ``-9`` degrees. Once again,
  80. create a key for both properties.
  81. |animation_final_keyframes|
  82. You can preview the result by clicking the play button or pressing :kbd:`Shift + D`.
  83. Click the stop button or press :kbd:`S` to stop playback.
  84. |image15|
  85. You can see that the engine interpolates between your keyframes to produce a
  86. continuous animation. At the moment, though, the motion feels very robotic. This
  87. is because the default interpolation is linear, causing constant transitions,
  88. unlike how living things move in the real world.
  89. We can control the transition between keyframes using easing curves.
  90. Click and drag around the first two keys in the timeline to box select them.
  91. |image16|
  92. You can edit the properties of both keys simultaneously in the *Inspector*,
  93. where you can see an *Easing* property.
  94. |image17|
  95. Click and drag on the curve, pulling it towards the left. This will make it
  96. ease-out, that is to say, transition fast initially and slow down as the time
  97. cursor reaches the next keyframe.
  98. |image18|
  99. Play the animation again to see the difference. The first half should already
  100. feel a bit bouncier.
  101. Apply an ease-out to the second keyframe in the rotation track.
  102. |image19|
  103. Do the opposite for the second position keyframe, dragging it to the right.
  104. |image20|
  105. Your animation should look something like this.
  106. |image21|
  107. .. note::
  108. Animations update the properties of the animated nodes every frame,
  109. overriding initial values. If we directly animated the *Player* node, it
  110. would prevent us from moving it in code. This is where the *Pivot* node
  111. comes in handy: even though we animated the *Character*, we can still move
  112. and rotate the *Pivot* and layer changes on top of the animation in a
  113. script.
  114. If you play the game, the player's creature will now float!
  115. If the creature is a little too close to the floor, you can move the ``Pivot`` up
  116. to offset it.
  117. Controlling the animation in code
  118. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  119. We can use code to control the animation playback based on the player's input.
  120. Let's change the animation speed when the character is moving.
  121. Open the ``Player``'s script by clicking the script icon next to it.
  122. |image22|
  123. In ``_physics_process()``, after the line where we check the ``direction``
  124. vector, add the following code.
  125. .. tabs::
  126. .. code-tab:: gdscript GDScript
  127. func _physics_process(delta):
  128. #...
  129. if direction != Vector3.ZERO:
  130. #...
  131. $AnimationPlayer.speed_scale = 4
  132. else:
  133. $AnimationPlayer.speed_scale = 1
  134. .. code-tab:: csharp
  135. public override void _PhysicsProcess(double delta)
  136. {
  137. // ...
  138. if (direction != Vector3.Zero)
  139. {
  140. // ...
  141. GetNode<AnimationPlayer>("AnimationPlayer").SpeedScale = 4;
  142. }
  143. else
  144. {
  145. GetNode<AnimationPlayer>("AnimationPlayer").SpeedScale = 1;
  146. }
  147. }
  148. This code makes it so when the player moves, we multiply the playback speed by
  149. ``4``. When they stop, we reset it to normal.
  150. We mentioned that the ``Pivot`` could layer transforms on top of the animation. We
  151. can make the character arc when jumping using the following line of code. Add it
  152. at the end of ``_physics_process()``.
  153. .. tabs::
  154. .. code-tab:: gdscript GDScript
  155. func _physics_process(delta):
  156. #...
  157. $Pivot.rotation.x = PI / 6 * velocity.y / jump_impulse
  158. .. code-tab:: csharp
  159. public override void _PhysicsProcess(double delta)
  160. {
  161. // ...
  162. var pivot = GetNode<Node3D>("Pivot");
  163. pivot.Rotation = new Vector3(Mathf.Pi / 6.0f * Velocity.Y / JumpImpulse, pivot.Rotation.Y, pivot.Rotation.Z);
  164. }
  165. Animating the mobs
  166. ------------------
  167. Here's another nice trick with animations in Godot: as long as you use a similar
  168. node structure, you can copy them to different scenes.
  169. For example, both the ``Mob`` and the ``Player`` scenes have a ``Pivot`` and a
  170. ``Character`` node, so we can reuse animations between them.
  171. Open the *Player* scene, select the AnimationPlayer node and open the "float"
  172. animation. Next, click on **Animation > Copy**. Then open ``mob.tscn``,
  173. create an AnimationPlayer child node and select it. Click **Animation > Paste**
  174. and make sure that the button with an "A+" icon (Autoplay on Load) and the
  175. looping arrows (Animation looping) are also turned on in the animation editor
  176. in the bottom panel. That's it; all monsters will now play the float animation.
  177. We can change the playback speed based on the creature's ``random_speed``. Open
  178. the *Mob*'s script and at the end of the ``initialize()`` function, add the
  179. following line.
  180. .. tabs::
  181. .. code-tab:: gdscript GDScript
  182. func initialize(start_position, player_position):
  183. #...
  184. $AnimationPlayer.speed_scale = random_speed / min_speed
  185. .. code-tab:: csharp
  186. public void Initialize(Vector3 startPosition, Vector3 playerPosition)
  187. {
  188. // ...
  189. GetNode<AnimationPlayer>("AnimationPlayer").SpeedScale = randomSpeed / MinSpeed;
  190. }
  191. And with that, you finished coding your first complete 3D game.
  192. **Congratulations**!
  193. In the next part, we'll quickly recap what you learned and give you some links
  194. to keep learning more. But for now, here are the complete ``Player.gd`` and
  195. ``Mob.gd`` so you can check your code against them.
  196. Here's the *Player* script.
  197. .. tabs::
  198. .. code-tab:: gdscript GDScript
  199. extends CharacterBody3D
  200. signal hit
  201. # How fast the player moves in meters per second.
  202. @export var speed = 14
  203. # The downward acceleration while in the air, in meters per second squared.
  204. @export var fall_acceleration = 75
  205. # Vertical impulse applied to the character upon jumping in meters per second.
  206. @export var jump_impulse = 20
  207. # Vertical impulse applied to the character upon bouncing over a mob
  208. # in meters per second.
  209. @export var bounce_impulse = 16
  210. var target_velocity = Vector3.ZERO
  211. func _physics_process(delta):
  212. # We create a local variable to store the input direction
  213. var direction = Vector3.ZERO
  214. # We check for each move input and update the direction accordingly
  215. if Input.is_action_pressed("move_right"):
  216. direction.x = direction.x + 1
  217. if Input.is_action_pressed("move_left"):
  218. direction.x = direction.x - 1
  219. if Input.is_action_pressed("move_back"):
  220. # Notice how we are working with the vector's x and z axes.
  221. # In 3D, the XZ plane is the ground plane.
  222. direction.z = direction.z + 1
  223. if Input.is_action_pressed("move_forward"):
  224. direction.z = direction.z - 1
  225. # Prevent diagonal movement being very fast
  226. if direction != Vector3.ZERO:
  227. direction = direction.normalized()
  228. $Pivot.look_at(position + direction,Vector3.UP)
  229. $AnimationPlayer.speed_scale = 4
  230. else:
  231. $AnimationPlayer.speed_scale = 1
  232. # Ground Velocity
  233. target_velocity.x = direction.x * speed
  234. target_velocity.z = direction.z * speed
  235. # Vertical Velocity
  236. if not is_on_floor(): # If in the air, fall towards the floor
  237. target_velocity.y = target_velocity.y - (fall_acceleration * delta)
  238. # Jumping.
  239. if is_on_floor() and Input.is_action_just_pressed("jump"):
  240. target_velocity.y = jump_impulse
  241. # Iterate through all collisions that occurred this frame
  242. # in C this would be for(int i = 0; i < collisions.Count; i++)
  243. for index in range(get_slide_collision_count()):
  244. # We get one of the collisions with the player
  245. var collision = get_slide_collision(index)
  246. # If the collision is with ground
  247. if collision.get_collider() == null:
  248. continue
  249. # If the collider is with a mob
  250. if collision.get_collider().is_in_group("mob"):
  251. var mob = collision.get_collider()
  252. # we check that we are hitting it from above.
  253. if Vector3.UP.dot(collision.get_normal()) > 0.1:
  254. # If so, we squash it and bounce.
  255. mob.squash()
  256. target_velocity.y = bounce_impulse
  257. # Prevent further duplicate calls.
  258. break
  259. # Moving the Character
  260. velocity = target_velocity
  261. move_and_slide()
  262. $Pivot.rotation.x = PI / 6 * velocity.y / jump_impulse
  263. # And this function at the bottom.
  264. func die():
  265. hit.emit()
  266. queue_free()
  267. func _on_mob_detector_body_entered(body):
  268. die()
  269. .. code-tab:: csharp
  270. using Godot;
  271. public partial class Player : CharacterBody3D
  272. {
  273. // Emitted when the player was hit by a mob.
  274. [Signal]
  275. public delegate void HitEventHandler();
  276. // How fast the player moves in meters per second.
  277. [Export]
  278. public int Speed { get; set; } = 14;
  279. // The downward acceleration when in the air, in meters per second squared.
  280. [Export]
  281. public int FallAcceleration { get; set; } = 75;
  282. // Vertical impulse applied to the character upon jumping in meters per second.
  283. [Export]
  284. public int JumpImpulse { get; set; } = 20;
  285. // Vertical impulse applied to the character upon bouncing over a mob in meters per second.
  286. [Export]
  287. public int BounceImpulse { get; set; } = 16;
  288. private Vector3 _targetVelocity = Vector3.Zero;
  289. public override void _PhysicsProcess(double delta)
  290. {
  291. // We create a local variable to store the input direction.
  292. var direction = Vector3.Zero;
  293. // We check for each move input and update the direction accordingly.
  294. if (Input.IsActionPressed("move_right"))
  295. {
  296. direction.X += 1.0f;
  297. }
  298. if (Input.IsActionPressed("move_left"))
  299. {
  300. direction.X -= 1.0f;
  301. }
  302. if (Input.IsActionPressed("move_back"))
  303. {
  304. // Notice how we are working with the vector's X and Z axes.
  305. // In 3D, the XZ plane is the ground plane.
  306. direction.Z += 1.0f;
  307. }
  308. if (Input.IsActionPressed("move_forward"))
  309. {
  310. direction.Z -= 1.0f;
  311. }
  312. // Prevent diagonal movement being very fast.
  313. if (direction != Vector3.Zero)
  314. {
  315. direction = direction.Normalized();
  316. GetNode<Node3D>("Pivot").LookAt(Position + direction, Vector3.Up);
  317. GetNode<AnimationPlayer>("AnimationPlayer").PlaybackSpeed = 4;
  318. }
  319. else
  320. {
  321. GetNode<AnimationPlayer>("AnimationPlayer").PlaybackSpeed = 1;
  322. }
  323. // Ground velocity
  324. _targetVelocity.X = direction.X * Speed;
  325. _targetVelocity.Z = direction.Z * Speed;
  326. // Vertical velocity
  327. if (!IsOnFloor())
  328. {
  329. _targetVelocity.Y -= FallAcceleration * (float)delta;
  330. }
  331. // Jumping.
  332. if (IsOnFloor() && Input.IsActionJustPressed("jump"))
  333. {
  334. _targetVelocity.Y += JumpImpulse;
  335. }
  336. // Iterate through all collisions that occurred this frame.
  337. for (int index = 0; index < GetSlideCollisionCount(); index++)
  338. {
  339. // We get one of the collisions with the player.
  340. KinematicCollision3D collision = GetSlideCollision(index);
  341. // If the collision is with a mob.
  342. if (collision.GetCollider() is Mob mob)
  343. {
  344. // We check that we are hitting it from above.
  345. if (Vector3.Up.Dot(collision.GetNormal()) > 0.1f)
  346. {
  347. // If so, we squash it and bounce.
  348. mob.Squash();
  349. _targetVelocity.Y = BounceImpulse;
  350. // Prevent further duplicate calls.
  351. break;
  352. }
  353. }
  354. }
  355. // Moving the character
  356. Velocity = _targetVelocity;
  357. MoveAndSlide();
  358. var pivot = GetNode<Node3D>("Pivot");
  359. pivot.Rotation = new Vector3(Mathf.Pi / 6.0f * Velocity.Y / JumpImpulse, pivot.Rotation.Y, pivot.Rotation.Z);
  360. }
  361. private void Die()
  362. {
  363. EmitSignal(SignalName.Hit);
  364. QueueFree();
  365. }
  366. private void OnMobDetectorBodyEntered(Node body)
  367. {
  368. Die();
  369. }
  370. }
  371. And the *Mob*'s script.
  372. .. tabs::
  373. .. code-tab:: gdscript GDScript
  374. extends CharacterBody3D
  375. # Minimum speed of the mob in meters per second.
  376. @export var min_speed = 10
  377. # Maximum speed of the mob in meters per second.
  378. @export var max_speed = 18
  379. # Emitted when the player jumped on the mob
  380. signal squashed
  381. func _physics_process(_delta):
  382. move_and_slide()
  383. # This function will be called from the Main scene.
  384. func initialize(start_position, player_position):
  385. # We position the mob by placing it at start_position
  386. # and rotate it towards player_position, so it looks at the player.
  387. look_at_from_position(start_position, player_position, Vector3.UP)
  388. # Rotate this mob randomly within range of -45 and +45 degrees,
  389. # so that it doesn't move directly towards the player.
  390. rotate_y(randf_range(-PI / 4, PI / 4))
  391. # We calculate a random speed (integer)
  392. var random_speed = randi_range(min_speed, max_speed)
  393. # We calculate a forward velocity that represents the speed.
  394. velocity = Vector3.FORWARD * random_speed
  395. # We then rotate the velocity vector based on the mob's Y rotation
  396. # in order to move in the direction the mob is looking.
  397. velocity = velocity.rotated(Vector3.UP, rotation.y)
  398. $AnimationPlayer.speed_scale = random_speed / min_speed
  399. func _on_visible_on_screen_notifier_3d_screen_exited():
  400. queue_free()
  401. func squash():
  402. squashed.emit()
  403. queue_free() # Destroy this node
  404. .. code-tab:: csharp
  405. using Godot;
  406. public partial class Mob : CharacterBody3D
  407. {
  408. // Emitted when the played jumped on the mob.
  409. [Signal]
  410. public delegate void SquashedEventHandler();
  411. // Minimum speed of the mob in meters per second
  412. [Export]
  413. public int MinSpeed { get; set; } = 10;
  414. // Maximum speed of the mob in meters per second
  415. [Export]
  416. public int MaxSpeed { get; set; } = 18;
  417. public override void _PhysicsProcess(double delta)
  418. {
  419. MoveAndSlide();
  420. }
  421. // This function will be called from the Main scene.
  422. public void Initialize(Vector3 startPosition, Vector3 playerPosition)
  423. {
  424. // We position the mob by placing it at startPosition
  425. // and rotate it towards playerPosition, so it looks at the player.
  426. LookAtFromPosition(startPosition, playerPosition, Vector3.Up);
  427. // Rotate this mob randomly within range of -45 and +45 degrees,
  428. // so that it doesn't move directly towards the player.
  429. RotateY((float)GD.RandRange(-Mathf.Pi / 4.0, Mathf.Pi / 4.0));
  430. // We calculate a random speed (integer).
  431. int randomSpeed = GD.RandRange(MinSpeed, MaxSpeed);
  432. // We calculate a forward velocity that represents the speed.
  433. Velocity = Vector3.Forward * randomSpeed;
  434. // We then rotate the velocity vector based on the mob's Y rotation
  435. // in order to move in the direction the mob is looking.
  436. Velocity = Velocity.Rotated(Vector3.Up, Rotation.Y);
  437. GetNode<AnimationPlayer>("AnimationPlayer").SpeedScale = randomSpeed / MinSpeed;
  438. }
  439. public void Squash()
  440. {
  441. EmitSignal(SignalName.Squashed);
  442. QueueFree(); // Destroy this node
  443. }
  444. private void OnVisibilityNotifierScreenExited()
  445. {
  446. QueueFree();
  447. }
  448. }
  449. .. |image0| image:: img/squash-the-creeps-final.gif
  450. .. |image1| image:: img/09.adding_animations/animation_player_dock.webp
  451. .. |image2| image:: img/09.adding_animations/02.new_animation.webp
  452. .. |image3| image:: img/09.adding_animations/03.float_name.png
  453. .. |image4| image:: img/09.adding_animations/03.timeline.png
  454. .. |image5| image:: img/09.adding_animations/04.autoplay_and_loop.png
  455. .. |image6| image:: img/09.adding_animations/05.pin_icon.png
  456. .. |image7| image:: img/09.adding_animations/06.animation_duration.webp
  457. .. |image8| image:: img/09.adding_animations/07.editable_timeline.webp
  458. .. |image9| image:: img/09.adding_animations/08.zoom_slider.webp
  459. .. |image10| image:: img/09.adding_animations/09.creating_first_keyframe.webp
  460. .. |image11| image:: img/09.adding_animations/10.initial_keys.webp
  461. .. |image12| image:: img/09.adding_animations/11.moving_keys.webp
  462. .. |image13| image:: img/09.adding_animations/12.second_keys_values.webp
  463. .. |image14| image:: img/09.adding_animations/13.second_keys.webp
  464. .. |image15| image:: img/09.adding_animations/14.play_button.png
  465. .. |image16| image:: img/09.adding_animations/15.box_select.webp
  466. .. |image17| image:: img/09.adding_animations/16.easing_property.png
  467. .. |image18| image:: img/09.adding_animations/17.ease_out.png
  468. .. |image19| image:: img/09.adding_animations/18.ease_out_second_rotation_key.png
  469. .. |image20| image:: img/09.adding_animations/19.ease_in_second_translation_key.png
  470. .. |image21| image:: img/09.adding_animations/20.float_animation.gif
  471. .. |image22| image:: img/09.adding_animations/21.script_icon.png
  472. .. |animation_final_keyframes| image:: img/09.adding_animations/animation_final_keyframes.webp
  473. .. |second_keys_both| image:: img/09.adding_animations/second_keys_both.webp
  474. .. |timeline_05_click| image:: img/09.adding_animations/timeline_05_click.webp