09.adding_animations.rst 21 KB

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