part_four.rst 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791
  1. .. _doc_fps_tutorial_part_four:
  2. Part 4
  3. ======
  4. Part overview
  5. -------------
  6. In this part, we will be adding health pickups, ammo pickups, targets the player can destroy, support for joypads, and add the ability to change weapons with the scroll wheel.
  7. .. image:: img/PartFourFinished.png
  8. .. note:: You are assumed to have finished :ref:`doc_fps_tutorial_part_three` before moving on to this part of the tutorial.
  9. The finished project from :ref:`doc_fps_tutorial_part_three` will be the starting project for part 4
  10. Let's get started!
  11. Adding joypad input
  12. -------------------
  13. .. note:: In Godot, any game controller is referred to as a joypad. This includes:
  14. Console controllers, Joysticks (like for flight simulators), Wheels (like for driving simulators), VR Controllers, and more!
  15. Firstly, we need to change a few things in our project's input map. Open up the project settings and select the ``Input Map`` tab.
  16. Now we need to add some joypad buttons to our various actions. Click the plus icon and select ``Joy Button``.
  17. .. image:: img/ProjectSettingsAddKey.png
  18. Feel free to use whatever button layout you want. Make sure that the device selected is set to ``0``. In the finished project, we will be using the following:
  19. * movement_sprint: ``Device 0, Button 4 (L, L1)``
  20. * fire: ``Device 0, Button 0 (PS Cross, XBox A, Nintendo B)``
  21. * reload: ``Device 0, Button 0 (PS Square, XBox X, Nintendo Y)``
  22. * flashlight: ``Device 0, Button 12 (D-Pad Up)``
  23. * shift_weapon_positive: ``Device 0, Button 15 (D-Pad Right)``
  24. * shift_weapon_negative: ``Device 0, Button 14 (D-Pad Left)``
  25. * fire_grenade: ``Device 0, Button 1 (PS Circle, XBox B, Nintendo A).``
  26. .. note:: These are already set up for you if you downloaded the starter assets
  27. Once you are happy with the input, close the project settings and save.
  28. ______
  29. Now let's open up ``Player.gd`` and add joypad input.
  30. First, we need to define a few new class variables. Add the following class variables to ``Player.gd``:
  31. ::
  32. # You may need to adjust depending on the sensitivity of your joypad
  33. var JOYPAD_SENSITIVITY = 2
  34. const JOYPAD_DEADZONE = 0.15
  35. Let's go over what each of these does:
  36. * ``JOYPAD_SENSITIVITY``: This is how fast the joypad's joysticks will move the camera.
  37. * ``JOYPAD_DEADZONE``: The dead zone for the joypad. You may need to adjust depending on your joypad.
  38. .. note:: Many joypads jitter around a certain point. To counter this, we ignore any movement
  39. within a radius of JOYPAD_DEADZONE. If we did not ignore said movement, the camera would jitter.
  40. Also, we are defining ``JOYPAD_SENSITIVITY`` as a variable instead of a constant because we'll later be changing it.
  41. Now we are ready to start handling joypad input!
  42. ______
  43. In ``process_input``, add the following code just before ``input_movement_vector = input_movement_vector.normalized()``:
  44. .. tabs::
  45. .. code-tab:: gdscript Xbox Controller
  46. # Add joypad input if one is present
  47. if Input.get_connected_joypads().size() > 0:
  48. var joypad_vec = Vector2(0, 0)
  49. if OS.get_name() == "Windows":
  50. joypad_vec = Vector2(Input.get_joy_axis(0, 0), -Input.get_joy_axis(0, 1))
  51. elif OS.get_name() == "X11":
  52. joypad_vec = Vector2(Input.get_joy_axis(0, 1), Input.get_joy_axis(0, 2))
  53. elif OS.get_name() == "OSX":
  54. joypad_vec = Vector2(Input.get_joy_axis(0, 1), Input.get_joy_axis(0, 2))
  55. if joypad_vec.length() < JOYPAD_DEADZONE:
  56. joypad_vec = Vector2(0, 0)
  57. else:
  58. joypad_vec = joypad_vec.normalized() * ((joypad_vec.length() - JOYPAD_DEADZONE) / (1 - JOYPAD_DEADZONE))
  59. input_movement_vector += joypad_vec
  60. .. code-tab:: gdscript PlayStation Controller
  61. # Add joypad input if one is present
  62. if Input.get_connected_joypads().size() > 0:
  63. var joypad_vec = Vector2(0, 0)
  64. if OS.get_name() == "Windows" or OS.get_name() == "X11":
  65. joypad_vec = Vector2(Input.get_joy_axis(0, 0), -Input.get_joy_axis(0, 1))
  66. elif OS.get_name() == "OSX":
  67. joypad_vec = Vector2(Input.get_joy_axis(0, 1), Input.get_joy_axis(0, 2))
  68. if joypad_vec.length() < JOYPAD_DEADZONE:
  69. joypad_vec = Vector2(0, 0)
  70. else:
  71. joypad_vec = joypad_vec.normalized() * ((joypad_vec.length() - JOYPAD_DEADZONE) / (1 - JOYPAD_DEADZONE))
  72. input_movement_vector += joypad_vec
  73. Let's go over what we're doing.
  74. Firstly, we check to see if there is a connected joypad.
  75. If there is a joypad connected, we then get its left stick axes for right/left and up/down.
  76. Because a wired Xbox 360 controller has different joystick axis mapping based on OS, we will use different axes based on
  77. the OS.
  78. .. warning:: This tutorial assumes you are using a XBox 360 or a PlayStation wired controller.
  79. Also, I do not (currently) have access to a Mac computer, so the joystick axes may need changing.
  80. If they do, please open a GitHub issue on the Godot documentation repository! Thanks!
  81. Next, we check to see if the joypad vector length is within the ``JOYPAD_DEADZONE`` radius.
  82. If it is, we set ``joypad_vec`` to an empty Vector2. If it is not, we use a scaled Radial Dead zone for precise dead zone calculation.
  83. .. note:: You can find a great article explaining all about how to handle joypad/controller dead zones
  84. `here <https://web.archive.org/web/20191208161810/http://www.third-helix.com/2013/04/12/doing-thumbstick-dead-zones-right.html>`__.
  85. We're using a translated version of the scaled radial dead zone code provided in that article.
  86. The article is a great read, and I highly suggest giving it a look!
  87. Finally, we add ``joypad_vec`` to ``input_movement_vector``.
  88. .. tip:: Remember how we normalize ``input_movement_vector``? This is why! If we did not normalize ``input_movement_vector``, the player could
  89. move faster if they pushed in the same direction with both the keyboard and the joypad!
  90. ______
  91. Make a new function called ``process_view_input`` and add the following:
  92. .. tabs::
  93. .. code-tab:: gdscript Xbox Controller
  94. func process_view_input(delta):
  95. if Input.get_mouse_mode() != Input.MOUSE_MODE_CAPTURED:
  96. return
  97. # NOTE: Until some bugs relating to captured mice are fixed, we cannot put the mouse view
  98. # rotation code here. Once the bug(s) are fixed, code for mouse view rotation code will go here!
  99. # ----------------------------------
  100. # Joypad rotation
  101. var joypad_vec = Vector2()
  102. if Input.get_connected_joypads().size() > 0:
  103. if OS.get_name() == "Windows":
  104. joypad_vec = Vector2(Input.get_joy_axis(0, 2), Input.get_joy_axis(0, 3))
  105. elif OS.get_name() == "X11":
  106. joypad_vec = Vector2(Input.get_joy_axis(0, 3), Input.get_joy_axis(0, 4))
  107. elif OS.get_name() == "OSX":
  108. joypad_vec = Vector2(Input.get_joy_axis(0, 3), Input.get_joy_axis(0, 4))
  109. if joypad_vec.length() < JOYPAD_DEADZONE:
  110. joypad_vec = Vector2(0, 0)
  111. else:
  112. joypad_vec = joypad_vec.normalized() * ((joypad_vec.length() - JOYPAD_DEADZONE) / (1 - JOYPAD_DEADZONE))
  113. rotation_helper.rotate_x(deg2rad(joypad_vec.y * JOYPAD_SENSITIVITY))
  114. rotate_y(deg2rad(joypad_vec.x * JOYPAD_SENSITIVITY * -1))
  115. var camera_rot = rotation_helper.rotation_degrees
  116. camera_rot.x = clamp(camera_rot.x, -70, 70)
  117. rotation_helper.rotation_degrees = camera_rot
  118. # ----------------------------------
  119. .. code-tab:: gdscript PlayStation Controller
  120. func process_view_input(delta):
  121. if Input.get_mouse_mode() != Input.MOUSE_MODE_CAPTURED:
  122. return
  123. # NOTE: Until some bugs relating to captured mice are fixed, we cannot put the mouse view
  124. # rotation code here. Once the bug(s) are fixed, code for mouse view rotation code will go here!
  125. # ----------------------------------
  126. # Joypad rotation
  127. var joypad_vec = Vector2()
  128. if Input.get_connected_joypads().size() > 0:
  129. if OS.get_name() == "Windows" or OS.get_name() == "X11":
  130. joypad_vec = Vector2(Input.get_joy_axis(0, 2), Input.get_joy_axis(0, 3))
  131. elif OS.get_name() == "OSX":
  132. joypad_vec = Vector2(Input.get_joy_axis(0, 3), Input.get_joy_axis(0, 4))
  133. if joypad_vec.length() < JOYPAD_DEADZONE:
  134. joypad_vec = Vector2(0, 0)
  135. else:
  136. joypad_vec = joypad_vec.normalized() * ((joypad_vec.length() - JOYPAD_DEADZONE) / (1 - JOYPAD_DEADZONE))
  137. rotation_helper.rotate_x(deg2rad(joypad_vec.y * JOYPAD_SENSITIVITY))
  138. rotate_y(deg2rad(joypad_vec.x * JOYPAD_SENSITIVITY * -1))
  139. var camera_rot = rotation_helper.rotation_degrees
  140. camera_rot.x = clamp(camera_rot.x, -70, 70)
  141. rotation_helper.rotation_degrees = camera_rot
  142. # ----------------------------------
  143. Let's go over what's happening:
  144. Firstly, we check the mouse mode. If the mouse mode is not ``MOUSE_MODE_CAPTURED``, we want to return, which will skip the code below.
  145. Next, we define a new :ref:`Vector2 <class_Vector2>` called ``joypad_vec``. This will hold the right joystick position. Based on the OS, we set its values so
  146. it is mapped to the proper axes for the right joystick.
  147. .. warning:: As stated above, I do not (currently) have access to a Mac computer, so the joystick axes may need changing. If they do,
  148. please open a GitHub issue on the Godot documentation repository! Thanks!
  149. We then account for the joypad's dead zone, exactly like in ``process_input``.
  150. Then, we rotate ``rotation_helper`` and the player's :ref:`KinematicBody <class_KinematicBody>` using ``joypad_vec``.
  151. Notice how the code that handles rotating the player and ``rotation_helper`` is exactly the same as the
  152. code in ``_input``. All we've done is change the values to use ``joypad_vec`` and ``JOYPAD_SENSITIVITY``.
  153. .. note:: Due to a few mouse-related bugs on Windows, we cannot put mouse rotation in ``process_view`` as well.
  154. Once these bugs are fixed, this will likely be updated to place the mouse rotation here in ``process_view_input`` as well.
  155. Finally, we clamp the camera's rotation so the player cannot look upside down.
  156. ______
  157. The last thing we need to do is add ``process_view_input`` to ``_physics_process``.
  158. Once ``process_view_input`` is added to ``_physics_process``, you should be able to play using a joypad!
  159. .. note:: I decided not to use the joypad triggers for firing because we'd then have to do some more axis managing, and because I prefer to use a shoulder buttons to fire.
  160. If you want to use the triggers for firing, you will need to change how firing works in ``process_input``. You need to get the axis values for the triggers,
  161. and check if it's over a certain value, say ``0.8`` for example. If it is, you add the same code as when the ``fire`` action was pressed.
  162. Adding mouse scroll wheel input
  163. -------------------------------
  164. Let's add one more input related feature before we start working on the pickups and the target. Let's add the ability to change weapons using the scroll wheel on the mouse.
  165. Open up ``Player.gd`` and add the following class variables:
  166. ::
  167. var mouse_scroll_value = 0
  168. const MOUSE_SENSITIVITY_SCROLL_WHEEL = 0.08
  169. Let's go over what each of these new variables will be doing:
  170. * ``mouse_scroll_value``: The value of the mouse scroll wheel.
  171. * ``MOUSE_SENSITIVITY_SCROLL_WHEEL``: How much a single scroll action increases mouse_scroll_value
  172. ______
  173. Now let's add the following to ``_input``:
  174. ::
  175. if event is InputEventMouseButton and Input.get_mouse_mode() == Input.MOUSE_MODE_CAPTURED:
  176. if event.button_index == BUTTON_WHEEL_UP or event.button_index == BUTTON_WHEEL_DOWN:
  177. if event.button_index == BUTTON_WHEEL_UP:
  178. mouse_scroll_value += MOUSE_SENSITIVITY_SCROLL_WHEEL
  179. elif event.button_index == BUTTON_WHEEL_DOWN:
  180. mouse_scroll_value -= MOUSE_SENSITIVITY_SCROLL_WHEEL
  181. mouse_scroll_value = clamp(mouse_scroll_value, 0, WEAPON_NUMBER_TO_NAME.size() - 1)
  182. if changing_weapon == false:
  183. if reloading_weapon == false:
  184. var round_mouse_scroll_value = int(round(mouse_scroll_value))
  185. if WEAPON_NUMBER_TO_NAME[round_mouse_scroll_value] != current_weapon_name:
  186. changing_weapon_name = WEAPON_NUMBER_TO_NAME[round_mouse_scroll_value]
  187. changing_weapon = true
  188. mouse_scroll_value = round_mouse_scroll_value
  189. Let's go over what's happening here:
  190. Firstly, we check if the event is an ``InputEventMouseButton`` event and that the mouse mode is ``MOUSE_MODE_CAPTURED``.
  191. Then, we check to see if the button index is either a ``BUTTON_WHEEL_UP`` or ``BUTTON_WHEEL_DOWN`` index.
  192. If the event's index is indeed a button wheel index, we then check to see if it is a ``BUTTON_WHEEL_UP`` or ``BUTTON_WHEEL_DOWN`` index.
  193. Based on whether it is up or down, we add or subtract ``MOUSE_SENSITIVITY_SCROLL_WHEEL`` to/from ``mouse_scroll_value``.
  194. Next, we clamp mouse scroll value to ensure it is inside the range of selectable weapons.
  195. We then check to see if the player is changing weapons or reloading. If the player is doing neither, we round ``mouse_scroll_value`` and cast it to an ``int``.
  196. .. note:: We are casting ``mouse_scroll_value`` to an ``int`` so we can use it as a key in our dictionary. If we left it as a float,
  197. we would get an error when we tried to run the project.
  198. Next, we check to see if the weapon name at ``round_mouse_scroll_value`` is not equal to the current weapon name using ``WEAPON_NUMBER_TO_NAME``.
  199. If the weapon is different from the player's current weapon, we assign ``changing_weapon_name``, set ``changing_weapon`` to ``true`` so the player will change weapons in
  200. ``process_changing_weapon``, and set ``mouse_scroll_value`` to ``round_mouse_scroll_value``.
  201. .. tip:: The reason we are setting ``mouse_scroll_value`` to the rounded scroll value is because we do not want the player to keep their
  202. mouse scroll wheel just in between values, giving them the ability to switch almost extremely fast. By assigning ``mouse_scroll_value``
  203. to ``round_mouse_scroll_value``, we ensure that each weapon takes exactly the same amount of scrolling to change.
  204. ______
  205. One more thing we need to change is in ``process_input``. In the code for changing weapons, add the following right after the line ``changing_weapon = true``:
  206. ::
  207. mouse_scroll_value = weapon_change_number
  208. Now the scroll value will be changed with the keyboard input. If we did not change this, the scroll value would be out of sync. If the scroll wheel were out of
  209. sync, scrolling forwards or backwards would not transition to the next/last weapon, but rather the next/last weapon the scroll wheel changed to.
  210. ______
  211. Now you can change weapons using the scroll wheel! Go give it a whirl!
  212. Adding the health pickups
  213. -------------------------
  214. Now that the player has health and ammo, we ideally need a way to replenish those resources.
  215. Open up ``Health_Pickup.tscn``.
  216. Expand ``Holder`` if it's not already expanded. Notice how we have two Spatial nodes, one called ``Health_Kit`` and another called ``Health_Kit_Small``.
  217. This is because we're actually going to be making two sizes of health pickups, one small and one large/normal. ``Health_Kit`` and ``Health_Kit_Small`` only
  218. have a single :ref:`MeshInstance <class_MeshInstance>` as their children.
  219. Next expand ``Health_Pickup_Trigger``. This is an :ref:`Area <class_Area>` node we're going to use to check if the player has walked close enough to pick up
  220. the health kit. If you expand it, you'll find two collision shapes, one for each size. We will be using a different collision shape size based on the size of the
  221. health pickup, so the smaller health pickup has a trigger collision shape closer to its size.
  222. The last thing to note is how we have an :ref:`AnimationPlayer <class_AnimationPlayer>` node so the health kit bobs and spins around slowly.
  223. Select ``Health_Pickup`` and add a new script called ``Health_Pickup.gd``. Add the following:
  224. ::
  225. extends Spatial
  226. export (int, "full size", "small") var kit_size = 0 setget kit_size_change
  227. # 0 = full size pickup, 1 = small pickup
  228. const HEALTH_AMOUNTS = [70, 30]
  229. const RESPAWN_TIME = 20
  230. var respawn_timer = 0
  231. var is_ready = false
  232. func _ready():
  233. $Holder/Health_Pickup_Trigger.connect("body_entered", self, "trigger_body_entered")
  234. is_ready = true
  235. kit_size_change_values(0, false)
  236. kit_size_change_values(1, false)
  237. kit_size_change_values(kit_size, true)
  238. func _physics_process(delta):
  239. if respawn_timer > 0:
  240. respawn_timer -= delta
  241. if respawn_timer <= 0:
  242. kit_size_change_values(kit_size, true)
  243. func kit_size_change(value):
  244. if is_ready:
  245. kit_size_change_values(kit_size, false)
  246. kit_size = value
  247. kit_size_change_values(kit_size, true)
  248. else:
  249. kit_size = value
  250. func kit_size_change_values(size, enable):
  251. if size == 0:
  252. $Holder/Health_Pickup_Trigger/Shape_Kit.disabled = !enable
  253. $Holder/Health_Kit.visible = enable
  254. elif size == 1:
  255. $Holder/Health_Pickup_Trigger/Shape_Kit_Small.disabled = !enable
  256. $Holder/Health_Kit_Small.visible = enable
  257. func trigger_body_entered(body):
  258. if body.has_method("add_health"):
  259. body.add_health(HEALTH_AMOUNTS[kit_size])
  260. respawn_timer = RESPAWN_TIME
  261. kit_size_change_values(kit_size, false)
  262. Let's go over what this script is doing, starting with its class variables:
  263. * ``kit_size``: The size of the health pickup. Notice how we're using a ``setget`` function to tell if it's changed.
  264. * ``HEALTH_AMMOUNTS``: The amount of health each pickup in each size contains.
  265. * ``RESPAWN_TIME``: The amount of time, in seconds, it takes for the health pickup to respawn
  266. * ``respawn_timer``: A variable used to track how long the health pickup has been waiting to respawn.
  267. * ``is_ready``: A variable to track whether the ``_ready`` function has been called or not.
  268. We're using ``is_ready`` because ``setget`` functions are called before ``_ready``; we need to ignore the
  269. first kit_size_change call, because we cannot access child nodes until ``_ready`` is called. If we did not ignore the
  270. first ``setget`` call, we would get several errors in the debugger.
  271. Also, notice how we are using an exported variable. This is so we can change the size of the health pickups in the editor. This makes it so
  272. we do not have to make two scenes for the two sizes, since we can easily change sizes in the editor using the exported variable.
  273. .. tip:: See :ref:`doc_GDScript` and scroll down to the Exports section for a list of export hints you can use.
  274. ______
  275. Let's look at ``_ready``:
  276. Firstly, we connect the ``body_entered`` signal from the ``Health_Pickup_Trigger`` to the ``trigger_body_entered`` function. This makes it so any
  277. body that enters the :ref:`Area <class_Area>` triggers the ``trigger_body_entered`` function.
  278. Next, we set ``is_ready`` to ``true`` so we can use the ``setget`` function.
  279. Then we hide all the possible kits and their collision shapes using ``kit_size_change_values``. The first argument is the size of the kit, while the second argument
  280. is whether to enable or disable the collision shape and mesh at that size.
  281. Then we make only the kit size we selected visible, calling ``kit_size_change_values`` and passing in ``kit_size`` and ``true``, so the size at ``kit_size`` is enabled.
  282. ______
  283. Next let's look at ``kit_size_change``.
  284. The first thing we do is check to see if ``is_ready`` is ``true``.
  285. If ``is_ready`` is ``true``, we then make whatever kit already assigned to ``kit_size`` disabled using ``kit_size_change_values``, passing in ``kit_size`` and ``false``.
  286. Then we assign ``kit_size`` to the new value passed in, ``value``. Then we call ``kit_size_change_values`` passing in ``kit_size`` again, but this time
  287. with the second argument as ``true`` so we enable it. Because we changed ``kit_size`` to the passed in value, this will make whatever kit size was passed in visible.
  288. If ``is_ready`` is not ``true``, we simply assign ``kit_size`` to the passed in ``value``.
  289. ______
  290. Now let's look at ``kit_size_change_values``.
  291. The first thing we do is check to see which size was passed in. Based on which size we want to enable/disable, we want to get different nodes.
  292. We get the collision shape for the node corresponding to ``size`` and disable it based on the ``enabled`` passed in argument/variable.
  293. .. note:: Why are we using ``!enable`` instead of ``enable``? This is so when we say we want to enable the node, we can pass in ``true``, but since
  294. :ref:`CollisionShape <class_CollisionShape>` uses disabled instead of enabled, we need to flip it. By flipping it, we can enable the collision shape
  295. and make the mesh visible when ``true`` is passed in.
  296. We then get the correct :ref:`Spatial <class_Spatial>` node holding the mesh and set its visibility to ``enable``.
  297. This function may be a little confusing; try to think of it like this: We're enabling/disabling the proper nodes for ``size`` using ``enabled``. This is so we cannot pick up
  298. health for a size that is not visible, and so only the mesh for the proper size will be visible.
  299. ______
  300. Finally, let's look at ``trigger_body_entered``.
  301. The first thing we do is check whether or not the body that has just entered has a method/function called ``add_health``. If it does, we then
  302. call ``add_health`` and pass in the health provided by the current kit size.
  303. Then we set ``respawn_timer`` to ``RESPAWN_TIME`` so the player has to wait before the player can get health again. Finally, call ``kit_size_change_values``,
  304. passing in ``kit_size`` and ``false`` so the kit at ``kit_size`` is invisible until it has waited long enough to respawn.
  305. _______
  306. The last thing we need to do before the player can use this health pickup is add a few things to ``Player.gd``.
  307. Open up ``Player.gd`` and add the following class variable:
  308. ::
  309. const MAX_HEALTH = 150
  310. * ``MAX_HEALTH``: The maximum amount of health a player can have.
  311. Now we need to add the ``add_health`` function to the player. Add the following to ``Player.gd``:
  312. ::
  313. func add_health(additional_health):
  314. health += additional_health
  315. health = clamp(health, 0, MAX_HEALTH)
  316. Let's quickly go over what this does.
  317. We first add ``additional_health`` to the player's current health. We then clamp the health so that it cannot take on a value higher than ``MAX_HEALTH``, nor a value lower
  318. than ``0``.
  319. _______
  320. With that done, the player can now collect health! Go place a few ``Health_Pickup`` scenes around and give it a try. You can change the size of the health pickup in the editor
  321. when a ``Health_Pickup`` instanced scene is selected, from a convenient drop down.
  322. Adding the ammo pickups
  323. -----------------------
  324. While adding health is good and all, we can't reap the rewards from adding it since nothing can (currently) damage us.
  325. Let's add some ammo pickups next!
  326. Open up ``Ammo_Pickup.tscn``. Notice how it's structured exactly the same as ``Health_Pickup.tscn``, but with the meshes and trigger collision shapes changed slightly to account
  327. for the difference in mesh sizes.
  328. Select ``Ammo_Pickup`` and add a new script called ``Ammo_Pickup.gd``. Add the following:
  329. ::
  330. extends Spatial
  331. export (int, "full size", "small") var kit_size = 0 setget kit_size_change
  332. # 0 = full size pickup, 1 = small pickup
  333. const AMMO_AMOUNTS = [4, 1]
  334. const RESPAWN_TIME = 20
  335. var respawn_timer = 0
  336. var is_ready = false
  337. func _ready():
  338. $Holder/Ammo_Pickup_Trigger.connect("body_entered", self, "trigger_body_entered")
  339. is_ready = true
  340. kit_size_change_values(0, false)
  341. kit_size_change_values(1, false)
  342. kit_size_change_values(kit_size, true)
  343. func _physics_process(delta):
  344. if respawn_timer > 0:
  345. respawn_timer -= delta
  346. if respawn_timer <= 0:
  347. kit_size_change_values(kit_size, true)
  348. func kit_size_change(value):
  349. if is_ready:
  350. kit_size_change_values(kit_size, false)
  351. kit_size = value
  352. kit_size_change_values(kit_size, true)
  353. else:
  354. kit_size = value
  355. func kit_size_change_values(size, enable):
  356. if size == 0:
  357. $Holder/Ammo_Pickup_Trigger/Shape_Kit.disabled = !enable
  358. $Holder/Ammo_Kit.visible = enable
  359. elif size == 1:
  360. $Holder/Ammo_Pickup_Trigger/Shape_Kit_Small.disabled = !enable
  361. $Holder/Ammo_Kit_Small.visible = enable
  362. func trigger_body_entered(body):
  363. if body.has_method("add_ammo"):
  364. body.add_ammo(AMMO_AMOUNTS[kit_size])
  365. respawn_timer = RESPAWN_TIME
  366. kit_size_change_values(kit_size, false)
  367. You may have noticed this code looks almost exactly the same as the health pickup. That's because it largely is the same! Only a few things
  368. have been changed, and that's what we're going to go over.
  369. Firstly, notice the change to ``AMMO_AMOUNTS`` from ``HEALTH_AMMOUNTS``. ``AMMO_AMOUNTS`` will be how many ammo clips/magazines the pickup adds to the current weapon.
  370. (Unlike in the case of ``HEALTH_AMMOUNTS``, which has stood for how many health points would be awarded, we add an entire clip to the current weapon instead of the raw ammo amount)
  371. The only other thing to notice is in ``trigger_body_entered``. We're checking for the existence of and calling a function called ``add_ammo`` instead of ``add_health``.
  372. Other than those two small changes, everything else is the same as the health pickup!
  373. _______
  374. All we need to do to make the ammo pickups work is add a new function to the player. Open ``Player.gd`` and add the following function:
  375. ::
  376. func add_ammo(additional_ammo):
  377. if (current_weapon_name != "UNARMED"):
  378. if (weapons[current_weapon_name].CAN_REFILL == true):
  379. weapons[current_weapon_name].spare_ammo += weapons[current_weapon_name].AMMO_IN_MAG * additional_ammo
  380. Let's go over what this function does.
  381. The first thing we check is whether the player is ``UNARMED``. Because ``UNARMED`` does not have a node/script, we want to make sure the player is not
  382. ``UNARMED`` before trying to get the node/script attached to ``current_weapon_name``.
  383. Next, we check to see if the current weapon can be refilled. If the current weapon can, we add a full clip/magazine worth of ammo to the weapon by
  384. multiplying the current weapon's ``AMMO_IN_MAG`` value by however many ammo clips we're adding (``additional_ammo``).
  385. _______
  386. With that done, you should now be able to get additional ammo! Go place some ammo pickups in one/both/all of the scenes and give it a try!
  387. .. note:: Notice how we're not limiting the amount of ammo you can carry. To limit the amount of ammo each weapon can carry, you need to add an additional variable to
  388. each weapon's script, and then clamp the weapon's ``spare_ammo`` variable after adding ammo in ``add_ammo``.
  389. Adding breakable targets
  390. ------------------------
  391. Before we end this part, let's add some targets.
  392. Open up ``Target.tscn`` and take a look at the scenes in the scene tree.
  393. Firstly, notice how we're not using a :ref:`RigidBody <class_RigidBody>` node, but a :ref:`StaticBody <class_StaticBody>` one.
  394. The reason behind this is our non-broken targets will not be moving anywhere; using a :ref:`RigidBody <class_RigidBody>` would be more hassle than
  395. it's worth since all it has to do is stay still.
  396. .. tip:: We also save a tiny bit of performance using a :ref:`StaticBody <class_StaticBody>` over a :ref:`RigidBody <class_RigidBody>`.
  397. The other thing to note is we have a node called ``Broken_Target_Holder``. This node is going to hold a spawned/instanced scene called
  398. ``Broken_Target.tscn``. Open up ``Broken_Target.tscn``.
  399. Notice how the target is broken up into five pieces, each a :ref:`RigidBody <class_RigidBody>` node. We're going to spawn/instance this scene when the target takes too much damage
  400. and needs to be destroyed. Then, we're going to hide the non-broken target, so it looks like the target shattered rather than a shattered target was
  401. spawned/instanced.
  402. While you still have ``Broken_Target.tscn`` open, attach ``RigidBody_hit_test.gd`` to all of the :ref:`RigidBody <class_RigidBody>` nodes. This will make
  403. it so the player can shoot at the broken pieces and they will react to the bullets.
  404. Alright, now switch back to ``Target.tscn``, select the ``Target`` :ref:`StaticBody <class_StaticBody>` node and create a new script called ``Target.gd``.
  405. Add the following code to ``Target.gd``:
  406. ::
  407. extends StaticBody
  408. const TARGET_HEALTH = 40
  409. var current_health = 40
  410. var broken_target_holder
  411. # The collision shape for the target.
  412. # NOTE: this is for the whole target, not the pieces of the target.
  413. var target_collision_shape
  414. const TARGET_RESPAWN_TIME = 14
  415. var target_respawn_timer = 0
  416. export (PackedScene) var destroyed_target
  417. func _ready():
  418. broken_target_holder = get_parent().get_node("Broken_Target_Holder")
  419. target_collision_shape = $Collision_Shape
  420. func _physics_process(delta):
  421. if target_respawn_timer > 0:
  422. target_respawn_timer -= delta
  423. if target_respawn_timer <= 0:
  424. for child in broken_target_holder.get_children():
  425. child.queue_free()
  426. target_collision_shape.disabled = false
  427. visible = true
  428. current_health = TARGET_HEALTH
  429. func bullet_hit(damage, bullet_transform):
  430. current_health -= damage
  431. if current_health <= 0:
  432. var clone = destroyed_target.instance()
  433. broken_target_holder.add_child(clone)
  434. for rigid in clone.get_children():
  435. if rigid is RigidBody:
  436. var center_in_rigid_space = broken_target_holder.global_transform.origin - rigid.global_transform.origin
  437. var direction = (rigid.transform.origin - center_in_rigid_space).normalized()
  438. # Apply the impulse with some additional force (I find 12 works nicely).
  439. rigid.apply_impulse(center_in_rigid_space, direction * 12 * damage)
  440. target_respawn_timer = TARGET_RESPAWN_TIME
  441. target_collision_shape.disabled = true
  442. visible = false
  443. Let's go over what this script does, starting with the class variables:
  444. * ``TARGET_HEALTH``: The amount of damage needed to break a fully healed target.
  445. * ``current_health``: The amount of health this target currently has.
  446. * ``broken_target_holder``: A variable to hold the ``Broken_Target_Holder`` node so we can use it easily.
  447. * ``target_collision_shape``: A variable to hold the :ref:`CollisionShape <class_CollisionShape>` for the non-broken target.
  448. * ``TARGET_RESPAWN_TIME``: The length of time, in seconds, it takes for a target to respawn.
  449. * ``target_respawn_timer``: A variable to track how long a target has been broken.
  450. * ``destroyed_target``: A :ref:`PackedScene <class_PackedScene>` to hold the broken target scene.
  451. Notice how we're using an exported variable (a :ref:`PackedScene <class_PackedScene>`) to get the broken target scene instead of
  452. using ``preload``. By using an exported variable, we can choose the scene from the editor, and if we need to use a different scene,
  453. it's as easy as selecting a different scene in the editor; we don't need to go to the code to change the scene we're using.
  454. ______
  455. Let's look at ``_ready``.
  456. The first thing we do is get the broken target holder and assign it to ``broken_target_holder``. Notice how we're using ``get_parent().get_node()`` here, instead
  457. of ``$``. If you wanted to use ``$``, then you'd need to change ``get_parent().get_node()`` to ``$"../Broken_Target_Holder"``.
  458. .. note:: At the time of when this was written, I did not realize you can use ``$"../NodeName"`` to get the parent nodes using ``$``, which is why ``get_parent().get_node()``
  459. is used instead.
  460. Next, we get the collision shape and assign it to ``target_collision_shape``. The reason we need the collision shape is because even when the mesh is invisible, the
  461. collision shape will still exist in the physics world. This makes it so the player could interact with a non-broken target even though it's invisible, which is
  462. not what we want. To get around this, we will disable/enable the collision shape as we make the mesh visible/invisible.
  463. ______
  464. Next let's look at ``_physics_process``.
  465. We're only going to be using ``_physics_process`` for respawning, and so the first thing we do is check to see if ``target_respawn_timer`` is greater than ``0``.
  466. If it is, we then subtract ``delta`` from it.
  467. Then we check to see if ``target_respawn_timer`` is ``0`` or less. The reason behind this is since we just removed ``delta`` from ``target_respawn_timer``, if it's
  468. ``0`` or less, then the target just got here, effectively allowing us to do whatever we need to do when the timer is finished.
  469. In this case, we want to respawn the target.
  470. The first thing we do is remove all children in the broken target holder. We do this by iterating over all of the children in ``broken_target_holder`` and free them using ``queue_free``.
  471. Next, we enable the collision shape by setting its ``disabled`` boolean to ``false``.
  472. Then we make the target, and all of its children nodes, visible again.
  473. Finally, we reset the target's health (``current_health``) to ``TARGET_HEALTH``.
  474. ______
  475. Finally, let's look at ``bullet_hit``.
  476. The first thing we do is subtract however much damage the bullet does from the target's health.
  477. Next we check to see if the target is at ``0`` health or lower. If it is, the target has just died and we need to spawn a broken target.
  478. We first instance a new destroyed target scene, and assign it to a new variable, a ``clone``.
  479. Next we add the ``clone`` as a child of the broken target holder.
  480. For bonus effect, we want to make all the target pieces explode outwards. To do this, we iterate over all the children in ``clone``.
  481. For each child, we first check to see if it's a :ref:`RigidBody <class_RigidBody>` node. If it is, we then calculate the center position of the target relative
  482. to the child node. Then we figure out which direction the child node is relative to the center. Using those calculated variables, we push the child from the calculated center,
  483. in the direction away from the center, using the damage of the bullet as the force.
  484. .. note:: We multiply the damage by ``12`` so it has a more dramatic effect. You can change this to a higher or lower value depending on how explosively you want
  485. your targets to shatter.
  486. Next, we set the target's respawn timer. We set the timer to ``TARGET_RESPAWN_TIME``, so it takes ``TARGET_RESPAWN_TIME`` in seconds until it is respawned.
  487. Then we disable the non-broken target's collision shape, and set the target's visibility to ``false``.
  488. ______
  489. .. warning:: Make sure to set the exported ``destroyed_target`` value for ``Target.tscn`` in the editor! Otherwise the targets will not be destroyed
  490. and you will get an error!
  491. With that done, go place some ``Target.tscn`` instances around in one/both/all of the levels. You should find they explode into five pieces after they've taken enough
  492. damage. After a little while, they'll respawn into a whole target again.
  493. Final notes
  494. -----------
  495. .. image:: img/PartFourFinished.png
  496. Now you can use a joypad, change weapons with the mouse's scroll wheel, replenish your health and ammo, and break targets with your weapons.
  497. In the next part, :ref:`doc_fps_tutorial_part_five`, we're going to add grenades to our player, give our player the ability to grab and throw objects, and
  498. add turrets!
  499. .. warning:: If you ever get lost, be sure to read over the code again!
  500. You can download the finished project for this part here: :download:`Godot_FPS_Part_4.zip <files/Godot_FPS_Part_4.zip>`