06.jump_and_squash.rst 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  1. .. _doc_first_3d_game_jumping_and_squashing_monsters:
  2. Jumping and squashing monsters
  3. ==============================
  4. In this part, we'll add the ability to jump, to squash the monsters. In the next
  5. lesson, we'll make the player die when a monster hits them on the ground.
  6. First, we have to change a few settings related to physics interactions. Enter
  7. the world of :ref:`physics layers
  8. <doc_physics_introduction_collision_layers_and_masks>`.
  9. Controlling physics interactions
  10. --------------------------------
  11. Physics bodies have access to two complementary properties: layers and masks.
  12. Layers define on which physics layer(s) an object is.
  13. Masks control the layers that a body will listen to and detect. This affects
  14. collision detection. When you want two bodies to interact, you need at least one
  15. to have a mask corresponding to the other.
  16. If that's confusing, don't worry, we'll see three examples in a second.
  17. The important point is that you can use layers and masks to filter physics
  18. interactions, control performance, and remove the need for extra conditions in
  19. your code.
  20. By default, all physics bodies and areas are set to both layer and mask ``0``.
  21. This means they all collide with each other.
  22. Physics layers are represented by numbers, but we can give them names to keep
  23. track of what's what.
  24. Setting layer names
  25. ~~~~~~~~~~~~~~~~~~~
  26. Let's give our physics layers a name. Go to *Project -> Project Settings*.
  27. |image0|
  28. In the left menu, navigate down to *Layer Names -> 3D Physics*. You can see a
  29. list of layers with a field next to each of them on the right. You can set their
  30. names there. Name the first three layers *player*, *enemies*, and *world*,
  31. respectively.
  32. |image1|
  33. Now, we can assign them to our physics nodes.
  34. Assigning layers and masks
  35. ~~~~~~~~~~~~~~~~~~~~~~~~~~
  36. In the *Main* scene, select the *Ground* node. In the *Inspector*, expand the
  37. *Collision* section. There, you can see the node's layers and masks as a grid of
  38. buttons.
  39. |image2|
  40. The ground is part of the world, so we want it to be part of the third layer.
  41. Click the lit button to toggle off the first *Layer* and toggle on the third
  42. one. Then, toggle off the *Mask* by clicking on it.
  43. |image3|
  44. As I mentioned above, the *Mask* property allows a node to listen to interaction
  45. with other physics objects, but we don't need it to have collisions. The
  46. *Ground* doesn't need to listen to anything; it's just there to prevent
  47. creatures from falling.
  48. Note that you can click the "..." button on the right side of the properties to
  49. see a list of named checkboxes.
  50. |image4|
  51. Next up are the *Player* and the *Mob*. Open ``Player.tscn`` by double-clicking
  52. the file in the *FileSystem* dock.
  53. Select the *Player* node and set its *Collision -> Mask* to both "enemies" and
  54. "world". You can leave the default *Layer* property as the first layer is the
  55. "player" one.
  56. |image5|
  57. Then, open the *Mob* scene by double-clicking on ``Mob.tscn`` and select the
  58. *Mob* node.
  59. Set its *Collision -> Layer* to "enemies" and unset its *Collision -> Mask*,
  60. leaving the mask empty.
  61. |image6|
  62. These settings mean the monsters will move through one another. If you want the
  63. monsters to collide with and slide against each other, turn on the "enemies"
  64. mask.
  65. .. note::
  66. The mobs don't need to mask the "world" layer because they only move
  67. on the XZ plane. We don't apply any gravity to them by design.
  68. Jumping
  69. -------
  70. The jumping mechanic itself requires only two lines of code. Open the *Player*
  71. script. We need a value to control the jump's strength and update
  72. ``_physics_process()`` to code the jump.
  73. After the line that defines ``fall_acceleration``, at the top of the script, add
  74. the ``jump_impulse``.
  75. .. tabs::
  76. .. code-tab:: gdscript GDScript
  77. #...
  78. # Vertical impulse applied to the character upon jumping in meters per second.
  79. export var jump_impulse = 20
  80. .. code-tab:: csharp
  81. // Don't forget to rebuild the project so the editor knows about the new export variable.
  82. // ...
  83. // Vertical impulse applied to the character upon jumping in meters per second.
  84. [Export]
  85. public int JumpImpulse = 20;
  86. Inside ``_physics_process()``, add the following code before the line where we
  87. called ``move_and_slide()``.
  88. .. tabs::
  89. .. code-tab:: gdscript GDScript
  90. func _physics_process(delta):
  91. #...
  92. # Jumping.
  93. if is_on_floor() and Input.is_action_just_pressed("jump"):
  94. velocity.y += jump_impulse
  95. #...
  96. .. code-tab:: csharp
  97. public override void _PhysicsProcess(float delta)
  98. {
  99. // ...
  100. // Jumping.
  101. if (IsOnFloor() && Input.IsActionJustPressed("jump"))
  102. {
  103. _velocity.y += JumpImpulse;
  104. }
  105. // ...
  106. }
  107. That's all you need to jump!
  108. The ``is_on_floor()`` method is a tool from the ``KinematicBody`` class. It
  109. returns ``true`` if the body collided with the floor in this frame. That's why
  110. we apply gravity to the *Player*: so we collide with the floor instead of
  111. floating over it like the monsters.
  112. If the character is on the floor and the player presses "jump", we instantly
  113. give them a lot of vertical speed. In games, you really want controls to be
  114. responsive and giving instant speed boosts like these, while unrealistic, feel
  115. great.
  116. Notice that the Y axis is positive upwards. That's unlike 2D, where the Y axis
  117. is positive downward.
  118. Squashing monsters
  119. ------------------
  120. Let's add the squash mechanic next. We're going to make the character bounce
  121. over monsters and kill them at the same time.
  122. We need to detect collisions with a monster and to differentiate them from
  123. collisions with the floor. To do so, we can use Godot's :ref:`group
  124. <doc_groups>` tagging feature.
  125. Open the scene ``Mob.tscn`` again and select the *Mob* node. Go to the *Node*
  126. dock on the right to see a list of signals. The *Node* dock has two tabs:
  127. *Signals*, which you've already used, and *Groups*, which allows you to assign
  128. tags to nodes.
  129. Click on it to reveal a field where you can write a tag name. Enter "mob" in the
  130. field and click the *Add* button.
  131. |image7|
  132. An icon appears in the *Scene* dock to indicate the node is part of at least one
  133. group.
  134. |image8|
  135. We can now use the group from the code to distinguish collisions with monsters
  136. from collisions with the floor.
  137. Coding the squash mechanic
  138. ~~~~~~~~~~~~~~~~~~~~~~~~~~
  139. Head back to the *Player* script to code the squash and bounce.
  140. At the top of the script, we need another property, ``bounce_impulse``. When
  141. squashing an enemy, we don't necessarily want the character to go as high up as
  142. when jumping.
  143. .. tabs::
  144. .. code-tab:: gdscript GDScript
  145. # Vertical impulse applied to the character upon bouncing over a mob in
  146. # meters per second.
  147. export var bounce_impulse = 16
  148. .. code-tab:: csharp
  149. // Don't forget to rebuild the project so the editor knows about the new export variable.
  150. // Vertical impulse applied to the character upon bouncing over a mob in meters per second.
  151. [Export]
  152. public int BounceImpulse = 16;
  153. Then, at the bottom of ``_physics_process()``, add the following loop. With
  154. ``move_and_slide()``, Godot makes the body move sometimes multiple times in a
  155. row to smooth out the character's motion. So we have to loop over all collisions
  156. that may have happened.
  157. In every iteration of the loop, we check if we landed on a mob. If so, we kill
  158. it and bounce.
  159. With this code, if no collisions occurred on a given frame, the loop won't run.
  160. .. tabs::
  161. .. code-tab:: gdscript GDScript
  162. func _physics_process(delta):
  163. #...
  164. for index in range(get_slide_count()):
  165. # We check every collision that occurred this frame.
  166. var collision = get_slide_collision(index)
  167. # If we collide with a monster...
  168. if collision.collider.is_in_group("mob"):
  169. var mob = collision.collider
  170. # ...we check that we are hitting it from above.
  171. if Vector3.UP.dot(collision.normal) > 0.1:
  172. # If so, we squash it and bounce.
  173. mob.squash()
  174. velocity.y = bounce_impulse
  175. .. code-tab:: csharp
  176. public override void _PhysicsProcess(float delta)
  177. {
  178. // ...
  179. for (int index = 0; index < GetSlideCount(); index++)
  180. {
  181. // We check every collision that occurred this frame.
  182. KinematicCollision collision = GetSlideCollision(index);
  183. // If we collide with a monster...
  184. if (collision.Collider is Mob mob && mob.IsInGroup("mob"))
  185. {
  186. // ...we check that we are hitting it from above.
  187. if (Vector3.Up.Dot(collision.Normal) > 0.1f)
  188. {
  189. // If so, we squash it and bounce.
  190. mob.Squash();
  191. _velocity.y = BounceImpulse;
  192. }
  193. }
  194. }
  195. }
  196. That's a lot of new functions. Here's some more information about them.
  197. The functions ``get_slide_count()`` and ``get_slide_collision()`` both come from
  198. the :ref:`KinematicBody<class_KinematicBody>` class and are related to
  199. ``move_and_slide()``.
  200. ``get_slide_collision()`` returns a
  201. :ref:`KinematicCollision<class_KinematicCollision>` object that holds
  202. information about where and how the collision occurred. For example, we use its
  203. ``collider`` property to check if we collided with a "mob" by calling
  204. ``is_in_group()`` on it: ``collision.collider.is_in_group("mob")``.
  205. .. note::
  206. The method ``is_in_group()`` is available on every :ref:`Node<class_Node>`.
  207. To check that we are landing on the monster, we use the vector dot product:
  208. ``Vector3.UP.dot(collision.normal) > 0.1``. The collision normal is a 3D vector
  209. that is perpendicular to the plane where the collision occurred. The dot product
  210. allows us to compare it to the up direction.
  211. With dot products, when the result is greater than ``0``, the two vectors are at
  212. an angle of fewer than 90 degrees. A value higher than ``0.1`` tells us that we
  213. are roughly above the monster.
  214. We are calling one undefined function, ``mob.squash()``. We have to add it to
  215. the Mob class.
  216. Open the script ``Mob.gd`` by double-clicking on it in the *FileSystem* dock. At
  217. the top of the script, we want to define a new signal named ``squashed``. And at
  218. the bottom, you can add the squash function, where we emit the signal and
  219. destroy the mob.
  220. .. tabs::
  221. .. code-tab:: gdscript GDScript
  222. # Emitted when the player jumped on the mob.
  223. signal squashed
  224. # ...
  225. func squash():
  226. emit_signal("squashed")
  227. queue_free()
  228. .. code-tab:: csharp
  229. // Don't forget to rebuild the project so the editor knows about the new signal.
  230. // Emitted when the played jumped on the mob.
  231. [Signal]
  232. public delegate void Squashed();
  233. // ...
  234. public void Squash()
  235. {
  236. EmitSignal(nameof(Squashed));
  237. QueueFree();
  238. }
  239. We will use the signal to add points to the score in the next lesson.
  240. With that, you should be able to kill monsters by jumping on them. You can press
  241. :kbd:`F5` to try the game and set ``Main.tscn`` as your project's main scene.
  242. However, the player won't die yet. We'll work on that in the next part.
  243. .. |image0| image:: img/06.jump_and_squash/02.project_settings.png
  244. .. |image1| image:: img/06.jump_and_squash/03.physics_layers.png
  245. .. |image2| image:: img/06.jump_and_squash/04.default_physics_properties.png
  246. .. |image3| image:: img/06.jump_and_squash/05.toggle_layer_and_mask.png
  247. .. |image4| image:: img/06.jump_and_squash/06.named_checkboxes.png
  248. .. |image5| image:: img/06.jump_and_squash/07.player_physics_mask.png
  249. .. |image6| image:: img/06.jump_and_squash/08.mob_physics_mask.png
  250. .. |image7| image:: img/06.jump_and_squash/09.groups_tab.png
  251. .. |image8| image:: img/06.jump_and_squash/10.group_scene_icon.png