06.jump_and_squash.rst 12 KB

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