04.mob_scene.rst 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  1. .. _doc_first_3d_game_designing_the_mob_scene:
  2. Designing the mob scene
  3. =======================
  4. In this part, you're going to code the monsters, which we'll call mobs. In the
  5. next lesson, we'll spawn them randomly around the playable area.
  6. Let's design the monsters themselves in a new scene. The node structure is going
  7. to be similar to the ``player.tscn`` scene.
  8. Create a scene with, once again, a :ref:`CharacterBody3D <class_CharacterBody3D>` node as its root. Name it
  9. ``Mob``. Add a child node :ref:`Node3D <class_Node3D>`, name it ``Pivot``. And drag and drop
  10. the file ``mob.glb`` from the *FileSystem* dock onto the ``Pivot`` to add the
  11. monster's 3D model to the scene.
  12. .. image:: img/04.mob_scene/drag_drop_mob.webp
  13. You can rename the newly created ``mob`` node
  14. into ``Character``.
  15. |image0|
  16. We need a collision shape for our body to work. Right-click on the ``Mob`` node,
  17. the scene's root, and click *Add Child Node*.
  18. |image1|
  19. Add a :ref:`CollisionShape3D <class_CollisionShape3D>`.
  20. |image2|
  21. In the *Inspector*, assign a *BoxShape3D* to the *Shape* property.
  22. .. image:: img/01.game_setup/08.create_box_shape3D.jpg
  23. We should change its size to fit the 3D model better. You can do so
  24. interactively by clicking and dragging on the orange dots.
  25. The box should touch the floor and be a little thinner than the model. Physics
  26. engines work in such a way that if the player's sphere touches even the box's
  27. corner, a collision will occur. If the box is a little too big compared to the
  28. 3D model, you may die at a distance from the monster, and the game will feel
  29. unfair to the players.
  30. |image4|
  31. Notice that my box is taller than the monster. It is okay in this game because
  32. we're looking at the scene from above and using a fixed perspective. Collision
  33. shapes don't have to match the model exactly. It's the way the game feels when
  34. you test it that should dictate their form and size.
  35. Removing monsters off-screen
  36. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  37. We're going to spawn monsters at regular time intervals in the game level. If
  38. we're not careful, their count could increase to infinity, and we don't want
  39. that. Each mob instance has both a memory and a processing cost, and we don't
  40. want to pay for it when the mob is outside the screen.
  41. Once a monster leaves the screen, we don't need it anymore, so we should delete it.
  42. Godot has a node that detects when objects leave the screen,
  43. :ref:`VisibleOnScreenNotifier3D <class_VisibleOnScreenNotifier3D>`, and we're going to use it to destroy our mobs.
  44. .. note::
  45. When you keep instancing an object, there's a technique you can
  46. use to avoid the cost of creating and destroying instances all the time
  47. called pooling. It consists of pre-creating an array of objects and reusing
  48. them over and over.
  49. When working with GDScript, you don't need to worry about this. The main
  50. reason to use pools is to avoid freezes with garbage-collected languages
  51. like C# or Lua. GDScript uses a different technique to manage memory,
  52. reference counting, which doesn't have that caveat. You can learn more
  53. about that here: :ref:`doc_gdscript_basics_memory_management`.
  54. Select the ``Mob`` node and add a child node :ref:`VisibleOnScreenNotifier3D <class_VisibleOnScreenNotifier3D>`. Another
  55. box, pink this time, appears. When this box completely leaves the screen, the
  56. node will emit a signal.
  57. |image5|
  58. Resize it using the orange dots until it covers the entire 3D model.
  59. |image6|
  60. Coding the mob's movement
  61. -------------------------
  62. Let's implement the monster's motion. We're going to do this in two steps.
  63. First, we'll write a script on the ``Mob`` that defines a function to initialize
  64. the monster. We'll then code the randomized spawn mechanism in the ``main.tscn`` scene
  65. and call the function from there.
  66. Attach a script to the ``Mob``.
  67. |image7|
  68. Here's the movement code to start with. We define two properties, ``min_speed``
  69. and ``max_speed``, to define a random speed range, which we will later use to define ``CharacterBody3D.velocity``.
  70. .. tabs::
  71. .. code-tab:: gdscript GDScript
  72. extends CharacterBody3D
  73. # Minimum speed of the mob in meters per second.
  74. @export var min_speed = 10
  75. # Maximum speed of the mob in meters per second.
  76. @export var max_speed = 18
  77. func _physics_process(_delta):
  78. move_and_slide()
  79. .. code-tab:: csharp
  80. using Godot;
  81. public partial class Mob : CharacterBody3D
  82. {
  83. // Don't forget to rebuild the project so the editor knows about the new export variable.
  84. // Minimum speed of the mob in meters per second
  85. [Export]
  86. public int MinSpeed { get; set; } = 10;
  87. // Maximum speed of the mob in meters per second
  88. [Export]
  89. public int MaxSpeed { get; set; } = 18;
  90. public override void _PhysicsProcess(double delta)
  91. {
  92. MoveAndSlide();
  93. }
  94. }
  95. Similarly to the player, we move the mob every frame by calling the function
  96. ``CharacterBody3D.move_and_slide()``. This time, we don't update
  97. the ``velocity`` every frame; we want the monster to move at a constant speed
  98. and leave the screen, even if it were to hit an obstacle.
  99. We need to define another function to calculate the ``CharacterBody3D.velocity``. This
  100. function will turn the monster towards the player and randomize both its angle
  101. of motion and its velocity.
  102. The function will take a ``start_position``,the mob's spawn position, and the
  103. ``player_position`` as its arguments.
  104. We position the mob at ``start_position`` and turn it towards the player using
  105. the ``look_at_from_position()`` method, and randomize the angle by rotating a
  106. random amount around the Y axis. Below, ``randf_range()`` outputs a random value
  107. between ``-PI / 4`` radians and ``PI / 4`` radians.
  108. .. tabs::
  109. .. code-tab:: gdscript GDScript
  110. # This function will be called from the Main scene.
  111. func initialize(start_position, player_position):
  112. # We position the mob by placing it at start_position
  113. # and rotate it towards player_position, so it looks at the player.
  114. look_at_from_position(start_position, player_position, Vector3.UP)
  115. # Rotate this mob randomly within range of -45 and +45 degrees,
  116. # so that it doesn't move directly towards the player.
  117. rotate_y(randf_range(-PI / 4, PI / 4))
  118. .. code-tab:: csharp
  119. // This function will be called from the Main scene.
  120. public void Initialize(Vector3 startPosition, Vector3 playerPosition)
  121. {
  122. // We position the mob by placing it at startPosition
  123. // and rotate it towards playerPosition, so it looks at the player.
  124. LookAtFromPosition(startPosition, playerPosition, Vector3.Up);
  125. // Rotate this mob randomly within range of -45 and +45 degrees,
  126. // so that it doesn't move directly towards the player.
  127. RotateY((float)GD.RandRange(-Mathf.Pi / 4.0, Mathf.Pi / 4.0));
  128. }
  129. We got a random position, now we need a ``random_speed``. ``randi_range()`` will be useful as it gives random int values, and we will use ``min_speed`` and ``max_speed``.
  130. ``random_speed`` is just an integer, and we just use it to multiply our ``CharacterBody3D.velocity``. After ``random_speed`` is applied, we rotate ``CharacterBody3D.velocity`` Vector3 towards the player.
  131. .. tabs::
  132. .. code-tab:: gdscript GDScript
  133. func initialize(start_position, player_position):
  134. # ...
  135. # We calculate a random speed (integer)
  136. var random_speed = randi_range(min_speed, max_speed)
  137. # We calculate a forward velocity that represents the speed.
  138. velocity = Vector3.FORWARD * random_speed
  139. # We then rotate the velocity vector based on the mob's Y rotation
  140. # in order to move in the direction the mob is looking.
  141. velocity = velocity.rotated(Vector3.UP, rotation.y)
  142. .. code-tab:: csharp
  143. public void Initialize(Vector3 startPosition, Vector3 playerPosition)
  144. {
  145. // ...
  146. // We calculate a random speed (integer).
  147. int randomSpeed = GD.RandRange(MinSpeed, MaxSpeed);
  148. // We calculate a forward velocity that represents the speed.
  149. Velocity = Vector3.Forward * randomSpeed;
  150. // We then rotate the velocity vector based on the mob's Y rotation
  151. // in order to move in the direction the mob is looking.
  152. Velocity = Velocity.Rotated(Vector3.Up, Rotation.Y);
  153. }
  154. Leaving the screen
  155. ------------------
  156. We still have to destroy the mobs when they leave the screen. To do so, we'll
  157. connect our :ref:`VisibleOnScreenNotifier3D <class_VisibleOnScreenNotifier3D>` node's ``screen_exited`` signal to the ``Mob``.
  158. Head back to the 3D viewport by clicking on the *3D* label at the top of the
  159. editor. You can also press :kbd:`Ctrl + F2` (:kbd:`Opt + 2` on macOS).
  160. |image8|
  161. Select the :ref:`VisibleOnScreenNotifier3D <class_VisibleOnScreenNotifier3D>` node and on the right side of the interface,
  162. navigate to the *Node* dock. Double-click the ``screen_exited()`` signal.
  163. |image9|
  164. Connect the signal to the ``Mob``
  165. |image10|
  166. This will add a new function for you in your mob script,
  167. ``_on_visible_on_screen_notifier_3d_screen_exited()``. From it, call the ``queue_free()``
  168. method. This function destroys the instance it's called on.
  169. .. tabs::
  170. .. code-tab:: gdscript GDScript
  171. func _on_visible_on_screen_notifier_3d_screen_exited():
  172. queue_free()
  173. .. code-tab:: csharp
  174. // We also specified this function name in PascalCase in the editor's connection window.
  175. private void OnVisibilityNotifierScreenExited()
  176. {
  177. QueueFree();
  178. }
  179. Our monster is ready to enter the game! In the next part, you will spawn
  180. monsters in the game level.
  181. Here is the complete ``mob.gd`` script for reference.
  182. .. tabs::
  183. .. code-tab:: gdscript GDScript
  184. extends CharacterBody3D
  185. # Minimum speed of the mob in meters per second.
  186. @export var min_speed = 10
  187. # Maximum speed of the mob in meters per second.
  188. @export var max_speed = 18
  189. func _physics_process(_delta):
  190. move_and_slide()
  191. # This function will be called from the Main scene.
  192. func initialize(start_position, player_position):
  193. # We position the mob by placing it at start_position
  194. # and rotate it towards player_position, so it looks at the player.
  195. look_at_from_position(start_position, player_position, Vector3.UP)
  196. # Rotate this mob randomly within range of -45 and +45 degrees,
  197. # so that it doesn't move directly towards the player.
  198. rotate_y(randf_range(-PI / 4, PI / 4))
  199. # We calculate a random speed (integer)
  200. var random_speed = randi_range(min_speed, max_speed)
  201. # We calculate a forward velocity that represents the speed.
  202. velocity = Vector3.FORWARD * random_speed
  203. # We then rotate the velocity vector based on the mob's Y rotation
  204. # in order to move in the direction the mob is looking.
  205. velocity = velocity.rotated(Vector3.UP, rotation.y)
  206. func _on_visible_on_screen_notifier_3d_screen_exited():
  207. queue_free()
  208. .. code-tab:: csharp
  209. using Godot;
  210. public partial class Mob : CharacterBody3D
  211. {
  212. // Minimum speed of the mob in meters per second.
  213. [Export]
  214. public int MinSpeed { get; set; } = 10;
  215. // Maximum speed of the mob in meters per second.
  216. [Export]
  217. public int MaxSpeed { get; set; } = 18;
  218. public override void _PhysicsProcess(double delta)
  219. {
  220. MoveAndSlide();
  221. }
  222. // This function will be called from the Main scene.
  223. public void Initialize(Vector3 startPosition, Vector3 playerPosition)
  224. {
  225. // We position the mob by placing it at startPosition
  226. // and rotate it towards playerPosition, so it looks at the player.
  227. LookAtFromPosition(startPosition, playerPosition, Vector3.Up);
  228. // Rotate this mob randomly within range of -45 and +45 degrees,
  229. // so that it doesn't move directly towards the player.
  230. RotateY((float)GD.RandRange(-Mathf.Pi / 4.0, Mathf.Pi / 4.0));
  231. // We calculate a random speed (integer).
  232. int randomSpeed = GD.RandRange(MinSpeed, MaxSpeed);
  233. // We calculate a forward velocity that represents the speed.
  234. Velocity = Vector3.Forward * randomSpeed;
  235. // We then rotate the velocity vector based on the mob's Y rotation
  236. // in order to move in the direction the mob is looking.
  237. Velocity = Velocity.Rotated(Vector3.Up, Rotation.Y);
  238. }
  239. // We also specified this function name in PascalCase in the editor's connection window.
  240. private void OnVisibilityNotifierScreenExited()
  241. {
  242. QueueFree();
  243. }
  244. }
  245. .. |image0| image:: img/04.mob_scene/01.initial_three_nodes.png
  246. .. |image1| image:: img/04.mob_scene/02.add_child_node.png
  247. .. |image2| image:: img/04.mob_scene/03.scene_with_collision_shape.png
  248. .. |image4| image:: img/04.mob_scene/05.box_final_size.png
  249. .. |image5| image:: img/04.mob_scene/06.visibility_notifier.png
  250. .. |image6| image:: img/04.mob_scene/07.visibility_notifier_bbox_resized.png
  251. .. |image7| image:: img/04.mob_scene/08.mob_attach_script.png
  252. .. |image8| image:: img/04.mob_scene/09.switch_to_3d_workspace.png
  253. .. |image9| image:: img/04.mob_scene/10.node_dock.webp
  254. .. |image10| image:: img/04.mob_scene/11.connect_signal.webp