part_three.rst 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684
  1. .. _doc_fps_tutorial_part_three:
  2. Part 3
  3. ======
  4. Part overview
  5. -------------
  6. In this part, we will be limiting the player's weapons by giving them ammo. We will also
  7. be giving the player the ability to reload, and we will be adding sounds when the
  8. weapons fire.
  9. .. image:: img/PartThreeFinished.png
  10. .. note:: You are assumed to have finished :ref:`doc_fps_tutorial_part_two` before moving on to this part of the tutorial.
  11. The finished project from :ref:`doc_fps_tutorial_part_two` will be the starting project for part 3
  12. Let's get started!
  13. Changing levels
  14. ---------------
  15. Now that we have a fully working FPS, let's move to a more FPS-like level.
  16. Open up ``Space_Level.tscn`` (``assets/Space_Level_Objects/Space_Level.tscn``) and/or ``Ruins_Level.tscn`` (``assets/Ruin_Level_Objects/Ruins_Level.tscn``).
  17. ``Space_Level.tscn`` and ``Ruins_Level.tscn`` are complete custom FPS levels created for the purpose of this tutorial. Press ``F6`` to
  18. play the open scene, or press the ``play current scene button``, and give each a try.
  19. .. warning:: ``Space_Level.tscn`` is more graphically demanding of the GPU than ``Ruins_Level.tscn``. If your computer is struggling to render
  20. ``Space_Level.tscn``, try using ``Ruins_Level.tscn`` instead.
  21. You might have noticed there are several :ref:`RigidBody <class_RigidBody>` nodes placed throughout the level.
  22. We can place ``RigidBody_hit_test.gd`` on them and then they will react to being hit with bullets, so let's do that!
  23. Follow the instructions below for either (or both) of the scenes you want to use
  24. .. tabs::
  25. .. code-tab:: gdscript Space_Level.tscn
  26. Expand "Other_Objects" and then expand "Physics_Objects".
  27. Expand one of the "Barrel_Group" nodes and then select "Barrel_Rigid_Body" and open it using
  28. the "Open in Editor" button.
  29. This will bring you to the "Barrel_Rigid_Body" scene. From there, select the root node and
  30. scroll the inspector down to the bottom.
  31. Select the drop down arrow under the "Node" tab, and then select "Load". Navigate to
  32. "RigidBody_hit_test.gd" and select "Open".
  33. Return back to "Space_Level.tscn".
  34. Expand one of the "Box_Group" nodes and then select "Crate_Rigid_Body" and open it using the
  35. "Open in Editor" button.
  36. This will bring you to the "Crate_Rigid_Body" scene. From there, select the root node and
  37. scroll the inspector down to the bottom.
  38. Select the drop down arrow under the "Node" tab, and then select "Load". Navigate to
  39. "RigidBody_hit_test.gd" and select "Open".
  40. Return to "Space_Level.tscn".
  41. .. code-tab:: gdscript Ruins_Level.tscn
  42. Expand "Misc_Objects" and then expand "Physics_Objects".
  43. Select all the "Stone_Cube" RigidBodies and then in the inspector scroll down to the bottom.
  44. Select the drop down arrow under the "Node" tab, and then select "Load". Navigate to
  45. "RigidBody_hit_test.gd" and select "Open".
  46. Return to "Ruins_Level.tscn".
  47. Now you can fire at all the rigid bodies in either level and they will react to bullets hitting them!
  48. Adding ammo
  49. -----------
  50. Now that the player has working guns, let's give them a limited amount of ammo.
  51. Firstly, we need to define a few variables in each of our weapon scripts.
  52. Open up ``Weapon_Pistol.gd`` and add the following class variables:
  53. ::
  54. var ammo_in_weapon = 10
  55. var spare_ammo = 20
  56. const AMMO_IN_MAG = 10
  57. * ``ammo_in_weapon``: The amount of ammo currently in the pistol
  58. * ``spare_ammo``: The amount of ammo we have left in reserve for the pistol
  59. * ``AMMO_IN_MAG``: The amount of ammo in a fully reloaded weapon/magazine
  60. Now all we need to do is add a single line of code to ``fire_weapon``.
  61. Add the following right under ``Clone.BULLET_DAMAGE = DAMAGE``: ``ammo_in_weapon -= 1``
  62. This will remove one from ``ammo_in_weapon`` every time the player fires. Notice we're not checking to see
  63. if the player has enough ammo or not in ``fire_weapon``. Instead, we're going to check to see if the player has enough ammo in ``Player.gd``.
  64. _______
  65. Now we need to add ammo for both the rifle and the knife.
  66. .. note:: You may be wondering why we are adding ammo for the knife given it does not consume any ammunition.
  67. The reason we want to add ammo to the knife is so we have a consistent interface for all our weapons.
  68. If we did not add ammo variables for the knife, we would have to add checks for the knife. By adding the ammo
  69. variables to the knife, we don't need to worry about whether or not all our weapons have the same variables.
  70. Add the following class variables to ``Weapon_Rifle.gd``:
  71. ::
  72. var ammo_in_weapon = 50
  73. var spare_ammo = 100
  74. const AMMO_IN_MAG = 50
  75. And then add the following to ``fire_weapon``: ``ammo_in_weapon -= 1``. Make sure that ``ammo_in_weapon -= 1`` is outside of the ``if ray.is_colliding()`` check so
  76. the player loses ammo regardless of whether the player hit something or not.
  77. Now all that's left is the knife. Add the following to ``Weapon_Knife.gd``:
  78. ::
  79. var ammo_in_weapon = 1
  80. var spare_ammo = 1
  81. const AMMO_IN_MAG = 1
  82. Because the knife does not consume ammo, that is all we need to add.
  83. _______
  84. Now we need to change one thing in ``Player.gd``, that is to say,
  85. how we're firing the weapons in ``process_input``. Change the code for firing weapons to the following:
  86. ::
  87. # ----------------------------------
  88. # Firing the weapons
  89. if Input.is_action_pressed("fire"):
  90. if changing_weapon == false:
  91. var current_weapon = weapons[current_weapon_name]
  92. if current_weapon != null:
  93. if current_weapon.ammo_in_weapon > 0:
  94. if animation_manager.current_state == current_weapon.IDLE_ANIM_NAME:
  95. animation_manager.set_animation(current_weapon.FIRE_ANIM_NAME)
  96. # ----------------------------------
  97. Now the weapons have a limited amount of ammo, and will stop firing when the player runs out.
  98. _______
  99. Ideally, we'd like to let the player be able to see how much ammo is left. Let's make a new function called ``process_UI``.
  100. First, add ``process_UI(delta)`` to ``_physics_process``.
  101. Now add the following to ``Player.gd``:
  102. ::
  103. func process_UI(delta):
  104. if current_weapon_name == "UNARMED" or current_weapon_name == "KNIFE":
  105. UI_status_label.text = "HEALTH: " + str(health)
  106. else:
  107. var current_weapon = weapons[current_weapon_name]
  108. UI_status_label.text = "HEALTH: " + str(health) + \
  109. "\nAMMO: " + str(current_weapon.ammo_in_weapon) + "/" + str(current_weapon.spare_ammo)
  110. Let's go over what's happening:
  111. Firstly, we check to see if the current weapon is either ``UNARMED`` or ``KNIFE``. If it is, we
  112. change the ``UI_status_label``'s text to only show the player's health since ``UNARMED`` and ``KNIFE`` do not consume ammo.
  113. If the player is using a weapon that consumes ammo, we first get the weapon node.
  114. Then we change ``UI_status_label``'s text to show the player's health, along with how much ammo the player has in the weapon
  115. and how much spare ammo the player has for that weapon.
  116. Now we can see how much ammo the player has through the HUD.
  117. Adding reloading to the weapons
  118. -------------------------------
  119. Now that the player can run out of ammo, we need a way to let the player fill them back up. Let's add reloading next!
  120. For reloading, we need to add a few more variables and a function to every weapon.
  121. Open up ``Weapon_Pistol.gd`` and add the following class variables:
  122. ::
  123. const CAN_RELOAD = true
  124. const CAN_REFILL = true
  125. const RELOADING_ANIM_NAME = "Pistol_reload"
  126. * ``CAN_RELOAD``: A boolean to track whether this weapon has the ability to reload
  127. * ``CAN_REFILL``: A boolean to track whether we can refill this weapon's spare ammo. We will not be using ``CAN_REFILL`` in this part, but we will in the next part!
  128. * ``RELOADING_ANIM_NAME``: The name of the reloading animation for this weapon.
  129. Now we need to add a function for handling reloading. Add the following function to ``Weapon_Pistol.gd``:
  130. ::
  131. func reload_weapon():
  132. var can_reload = false
  133. if player_node.animation_manager.current_state == IDLE_ANIM_NAME:
  134. can_reload = true
  135. if spare_ammo <= 0 or ammo_in_weapon == AMMO_IN_MAG:
  136. can_reload = false
  137. if can_reload == true:
  138. var ammo_needed = AMMO_IN_MAG - ammo_in_weapon
  139. if spare_ammo >= ammo_needed:
  140. spare_ammo -= ammo_needed
  141. ammo_in_weapon = AMMO_IN_MAG
  142. else:
  143. ammo_in_weapon += spare_ammo
  144. spare_ammo = 0
  145. player_node.animation_manager.set_animation(RELOADING_ANIM_NAME)
  146. return true
  147. return false
  148. Let's go over what's happening:
  149. First we define a variable to see whether or not this weapon can reload.
  150. Then we check to see if the player is in this weapon's idle animation state because we only want to be able to reload when the player is not
  151. firing, equipping, or unequipping.
  152. Next we check to see if the player has spare ammo, and if the ammo already in the weapon is equal to a fully reloaded weapon.
  153. This way we can ensure the player cannot reload when the player has no ammo or when the weapon is already full of ammo.
  154. If we can still reload, then we calculate the amount of ammo needed to reload the weapon.
  155. If the player has enough ammo to fill the weapon, we remove the ammo needed from ``spare_ammo`` and then set ``ammo_in_weapon`` to a full weapon/magazine.
  156. If the player does not have enough ammo, we add all the ammo left in ``spare_ammo``, and then set ``spare_ammo`` to ``0``.
  157. Next we play the reloading animation for this weapon, and then return ``true``.
  158. If the player could not reload, we return ``false``.
  159. _______
  160. Now we need to add reloading to the rifle. Open up ``Weapon_Rifle.gd`` and add the following class variables:
  161. ::
  162. const CAN_RELOAD = true
  163. const CAN_REFILL = true
  164. const RELOADING_ANIM_NAME = "Rifle_reload"
  165. These variables are exactly the same as the pistol, just with ``RELOADING_ANIM_NAME`` changed to the rifle's reloading animation.
  166. Now we need to add ``reload_weapon`` to ``Weapon_Rifle.gd``:
  167. ::
  168. func reload_weapon():
  169. var can_reload = false
  170. if player_node.animation_manager.current_state == IDLE_ANIM_NAME:
  171. can_reload = true
  172. if spare_ammo <= 0 or ammo_in_weapon == AMMO_IN_MAG:
  173. can_reload = false
  174. if can_reload == true:
  175. var ammo_needed = AMMO_IN_MAG - ammo_in_weapon
  176. if spare_ammo >= ammo_needed:
  177. spare_ammo -= ammo_needed
  178. ammo_in_weapon = AMMO_IN_MAG
  179. else:
  180. ammo_in_weapon += spare_ammo
  181. spare_ammo = 0
  182. player_node.animation_manager.set_animation(RELOADING_ANIM_NAME)
  183. return true
  184. return false
  185. This code is exactly the same as the one for the pistol.
  186. _______
  187. The last bit we need to do for the weapons is add 'reloading' to the knife. Add the following class variables to ``Weapon_Knife.gd``:
  188. ::
  189. const CAN_RELOAD = false
  190. const CAN_REFILL = false
  191. const RELOADING_ANIM_NAME = ""
  192. Since we both cannot reload or refill a knife, we set both constants to ``false``. We also define ``RELOADING_ANIM_NAME`` as an empty string, since the knife
  193. has no reloading animation.
  194. Now we need to add ``reloading_weapon``:
  195. ::
  196. func reload_weapon():
  197. return false
  198. Since we cannot reload a knife, we always return ``false``.
  199. Adding reloading to the player
  200. ------------------------------
  201. Now we need to add a few things to ``Player.gd``. First we need to define a new class variable:
  202. ::
  203. var reloading_weapon = false
  204. * ``reloading_weapon``: A variable to track whether or not the player is currently trying to reload.
  205. Next we need to add another function call to ``_physics_process``.
  206. Add ``process_reloading(delta)`` to ``_physics_process``. Now ``_physics_process`` should look something like this:
  207. ::
  208. func _physics_process(delta):
  209. process_input(delta)
  210. process_movement(delta)
  211. process_changing_weapons(delta)
  212. process_reloading(delta)
  213. process_UI(delta)
  214. Now we need to add ``process_reloading``. Add the following function to ``Player.gd``:
  215. ::
  216. func process_reloading(delta):
  217. if reloading_weapon == true:
  218. var current_weapon = weapons[current_weapon_name]
  219. if current_weapon != null:
  220. current_weapon.reload_weapon()
  221. reloading_weapon = false
  222. Let's go over what's happening here.
  223. Firstly, we check to make sure the player is trying to reload.
  224. If the player is trying to reload, we then get the current weapon. If the current weapon does not equal ``null``, we call its ``reload_weapon`` function.
  225. .. note:: If the current weapon is equal to ``null``, then the current weapon is ``UNARMED``.
  226. Finally, we set ``reloading_weapon`` to ``false`` because, regardless of whether the player successfully reloaded, we've tried reloading
  227. and no longer need to keep trying.
  228. _______
  229. Before we can let the player reload, we need to change a few things in ``process_input``.
  230. The first thing we need to change is in the code for changing weapons. We need to add an additional check (``if reloading_weapon == false:``) to see if the player is reloading:
  231. ::
  232. if changing_weapon == false:
  233. # New line of code here!
  234. if reloading_weapon == false:
  235. if WEAPON_NUMBER_TO_NAME[weapon_change_number] != current_weapon_name:
  236. changing_weapon_name = WEAPON_NUMBER_TO_NAME[weapon_change_number]
  237. changing_weapon = true
  238. This makes it so the player cannot change weapons if the player is reloading.
  239. Now we need to add the code to trigger a reload when the player pushes the ``reload`` action. Add the following code to ``process_input``:
  240. ::
  241. # ----------------------------------
  242. # Reloading
  243. if reloading_weapon == false:
  244. if changing_weapon == false:
  245. if Input.is_action_just_pressed("reload"):
  246. var current_weapon = weapons[current_weapon_name]
  247. if current_weapon != null:
  248. if current_weapon.CAN_RELOAD == true:
  249. var current_anim_state = animation_manager.current_state
  250. var is_reloading = false
  251. for weapon in weapons:
  252. var weapon_node = weapons[weapon]
  253. if weapon_node != null:
  254. if current_anim_state == weapon_node.RELOADING_ANIM_NAME:
  255. is_reloading = true
  256. if is_reloading == false:
  257. reloading_weapon = true
  258. # ----------------------------------
  259. Let's go over what's happening here.
  260. First we make sure the player is not reloading already, nor is the player trying to change weapons.
  261. Then we check to see if the ``reload`` action has been pressed.
  262. If the player has pressed ``reload``, we then get the current weapon and check to make sure it is not ``null``. Then we check to see whether the
  263. weapon can reload or not using its ``CAN_RELOAD`` constant.
  264. If the weapon can reload, we then get the current animation state, and make a variable for tracking whether the player is already reloading or not.
  265. We then go through every weapon to make sure the player is not already playing that weapon's reloading animation.
  266. If the player is not reloading any weapon, we set ``reloading_weapon`` to ``true``.
  267. _______
  268. One thing I like to add is where the weapon will reload itself if you try to fire it and it's out of ammo.
  269. We also need to add an additional if check (``is_reloading_weapon == false:``) so the player cannot fire the current weapon while
  270. reloading.
  271. Let's change our firing code in ``process_input`` so it reloads when trying to fire an empty weapon:
  272. ::
  273. # ----------------------------------
  274. # Firing the weapons
  275. if Input.is_action_pressed("fire"):
  276. if reloading_weapon == false:
  277. if changing_weapon == false:
  278. var current_weapon = weapons[current_weapon_name]
  279. if current_weapon != null:
  280. if current_weapon.ammo_in_weapon > 0:
  281. if animation_manager.current_state == current_weapon.IDLE_ANIM_NAME:
  282. animation_manager.set_animation(current_weapon.FIRE_ANIM_NAME)
  283. else:
  284. reloading_weapon = true
  285. # ----------------------------------
  286. Now we check to make sure the player is not reloading before we fire the weapon, and when we have ``0`` or less ammo in the current weapon,
  287. we set ``reloading_weapon`` to ``true`` if the player tries to fire.
  288. This will make it so the player will try to reload when attempting to fire an empty weapon.
  289. _______
  290. With that done, the player can now reload! Give it a try! Now you can fire all the spare ammo for each weapon.
  291. Adding sounds
  292. -------------
  293. Finally, let's add some sounds that accompany the player firing, reloading and changing weapons.
  294. .. tip:: There are no game sounds provided in this tutorial (for legal reasons).
  295. https://gamesounds.xyz/ is a collection of **"royalty free or public domain music and sounds suitable for games"**.
  296. I used Gamemaster's Gun Sound Pack, which can be found in the Sonniss.com GDC 2017 Game Audio Bundle.
  297. Open up ``Simple_Audio_Player.tscn``. It is simply a :ref:`Spatial <class_Spatial>` with an :ref:`AudioStreamPlayer <class_AudioStreamPlayer>` as its child.
  298. .. note:: The reason this is called a 'simple' audio player is because we are not taking performance into account
  299. and because the code is designed to provide sound in the simplest way possible.
  300. If you want to use 3D audio, so it sounds like it's coming from a location in 3D space, right click
  301. the :ref:`AudioStreamPlayer <class_AudioStreamPlayer>` and select "Change type".
  302. This will open the node browser. Navigate to :ref:`AudioStreamPlayer3D <class_AudioStreamPlayer3D>` and select "change".
  303. In the source for this tutorial, we will be using :ref:`AudioStreamPlayer <class_AudioStreamPlayer>`, but you can optionally
  304. use :ref:`AudioStreamPlayer3D <class_AudioStreamPlayer3D>` if you desire, and the code provided below will work regardless of which
  305. one you chose.
  306. Create a new script and call it ``Simple_Audio_Player.gd``. Attach it to the :ref:`Spatial <class_Spatial>` in ``Simple_Audio_Player.tscn``
  307. and insert the following code:
  308. ::
  309. extends Spatial
  310. # All of the audio files.
  311. # You will need to provide your own sound files.
  312. var audio_pistol_shot = preload("res://path_to_your_audio_here")
  313. var audio_gun_cock = preload("res://path_to_your_audio_here")
  314. var audio_rifle_shot = preload("res://path_to_your_audio_here")
  315. var audio_node = null
  316. func _ready():
  317. audio_node = $Audio_Stream_Player
  318. audio_node.connect("finished", self, "destroy_self")
  319. audio_node.stop()
  320. func play_sound(sound_name, position=null):
  321. if audio_pistol_shot == null or audio_rifle_shot == null or audio_gun_cock == null:
  322. print ("Audio not set!")
  323. queue_free()
  324. return
  325. if sound_name == "Pistol_shot":
  326. audio_node.stream = audio_pistol_shot
  327. elif sound_name == "Rifle_shot":
  328. audio_node.stream = audio_rifle_shot
  329. elif sound_name == "Gun_cock":
  330. audio_node.stream = audio_gun_cock
  331. else:
  332. print ("UNKNOWN STREAM")
  333. queue_free()
  334. return
  335. # If you are using an AudioStreamPlayer3D, then uncomment these lines to set the position.
  336. #if audio_node is AudioStreamPlayer3D:
  337. # if position != null:
  338. # audio_node.global_transform.origin = position
  339. audio_node.play()
  340. func destroy_self():
  341. audio_node.stop()
  342. queue_free()
  343. .. tip:: By setting ``position`` to ``null`` by default in ``play_sound``, we are making it an optional argument,
  344. meaning ``position`` doesn't necessarily have to be passed in to call ``play_sound``.
  345. Let's go over what's happening here:
  346. _________
  347. In ``_ready``, we get the :ref:`AudioStreamPlayer <class_AudioStreamPlayer>` and connect its ``finished`` signal to the ``destroy_self`` function.
  348. It doesn't matter if it's an :ref:`AudioStreamPlayer <class_AudioStreamPlayer>` or :ref:`AudioStreamPlayer3D <class_AudioStreamPlayer3D>` node,
  349. as they both have the finished signal. To make sure it is not playing any sounds, we call ``stop`` on the :ref:`AudioStreamPlayer <class_AudioStreamPlayer>`.
  350. .. warning:: Make sure your sound files are **not** set to loop! If it is set to loop,
  351. the sounds will continue to play infinitely and the script will not work!
  352. The ``play_sound`` function is what we will be calling from ``Player.gd``. We check if the sound
  353. is one of the three possible sounds, and if it is one of the three sounds we set the audio stream in :ref:`AudioStreamPlayer <class_AudioStreamPlayer>`
  354. to the correct sound.
  355. If it is an unknown sound, we print an error message to the console and free the audio player.
  356. If you are using an :ref:`AudioStreamPlayer3D <class_AudioStreamPlayer3D>`, remove the ``#`` to set the position of
  357. the audio player node so it plays at the correct position.
  358. Finally, we tell the :ref:`AudioStreamPlayer <class_AudioStreamPlayer>` to play.
  359. When the :ref:`AudioStreamPlayer <class_AudioStreamPlayer>` is finished playing the sound, it will call ``destroy_self`` because
  360. we connected the ``finished`` signal in ``_ready``. We stop the :ref:`AudioStreamPlayer <class_AudioStreamPlayer>` and free the audio player
  361. to save on resources.
  362. .. note:: This system is extremely simple and has some major flaws:
  363. One flaw is we have to pass in a string value to play a sound. While it is relatively simple
  364. to remember the names of the three sounds, it can be increasingly complex when you have more sounds.
  365. Ideally, we'd place these sounds in some sort of container with exposed variables so we do not have
  366. to remember the name(s) of each sound effect we want to play.
  367. Another flaw is we cannot play looping sounds effects, nor background music, easily with this system.
  368. Because we cannot play looping sounds, certain effects, like footstep sounds, are harder to accomplish
  369. because we then have to keep track of whether or not there is a sound effect and whether or not we
  370. need to continue playing it.
  371. One of the biggest flaws with this system is we can only play sounds from ``Player.gd``.
  372. Ideally we'd like to be able to play sounds from any script at any time.
  373. _________
  374. With that done, let's open up ``Player.gd`` again.
  375. First we need to load the ``Simple_Audio_Player.tscn``. Place the following code in the class variables section of the script:
  376. ::
  377. var simple_audio_player = preload("res://Simple_Audio_Player.tscn")
  378. Now we need to instance the simple audio player when we need it, and then call its
  379. ``play_sound`` function and pass the name of the sound we want to play. To make the process simpler,
  380. let's create a ``create_sound`` function in ``Player.gd``:
  381. ::
  382. func create_sound(sound_name, position=null):
  383. var audio_clone = simple_audio_player.instance()
  384. var scene_root = get_tree().root.get_children()[0]
  385. scene_root.add_child(audio_clone)
  386. audio_clone.play_sound(sound_name, position)
  387. Let's walk through what this function does:
  388. _________
  389. The first line instances the ``Simple_Audio_Player.tscn`` scene and assigns it to a variable
  390. named ``audio_clone``.
  391. The second line gets the scene root, and this has a large (though safe) assumption.
  392. We first get this node's :ref:`SceneTree <class_SceneTree>`,
  393. and then access the root node, which in this case is the :ref:`Viewport <class_Viewport>` this entire game is running under.
  394. Then we get the first child of the :ref:`Viewport <class_Viewport>`, which in our case happens to be the root node in
  395. ``Test_Area.tscn`` or any of the other provided levels. **We are making a huge assumption that the first child of the root node
  396. is the root scene that the player is under, which may not always be the case**.
  397. If this doesn't make sense to you, don't worry too much about it. The second line of code only does not work
  398. reliably if you have multiple scenes loaded as children of the root node at a time, which will rarely happen for most projects and will not be happening in this tutorial series.
  399. This is only potentially a issue depending on how you handle scene loading.
  400. The third line adds our newly created ``Simple_Audio_Player`` scene to be a child of the scene root. This
  401. works exactly the same as when we are spawning bullets.
  402. Finally, we call the ``play_sound`` function and pass in the arguments passed in to ``create_sound``. This will call
  403. ``Simple_Audio_Player.gd``'s ``play_sound`` function with the passed in arguments.
  404. _________
  405. Now all that is left is playing the sounds when we want to. Let's add sound to the pistol first!
  406. Open up ``Weapon_Pistol.gd``.
  407. Now, we want to make a noise when the player fires the pistol, so add the following to the end of the ``fire_weapon`` function:
  408. ::
  409. player_node.create_sound("Pistol_shot", self.global_transform.origin)
  410. Now when the player fires the pistol, we'll play the ``Pistol_shot`` sound.
  411. To make a sound when the player reloads, we need to add the following right under ``player_node.animation_manager.set_animation(RELOADING_ANIM_NAME)`` in the
  412. ``reload_weapon`` function:
  413. ::
  414. player_node.create_sound("Gun_cock", player_node.camera.global_transform.origin)
  415. Now when the player reloads, we'll play the ``Gun_cock`` sound.
  416. _________
  417. Now let's add sounds to the rifle.
  418. Open up ``Weapon_Rifle.gd``.
  419. To play sounds when the rifle is fired, add the following to the end of the ``fire_weapon`` function:
  420. ::
  421. player_node.create_sound("Rifle_shot", ray.global_transform.origin)
  422. Now when the player fires the rifle, we'll play the ``Rifle_shot`` sound.
  423. To make a sound when the player reloads, we need to add the following right under ``player_node.animation_manager.set_animation(RELOADING_ANIM_NAME)`` in the
  424. ``reload_weapon`` function:
  425. ::
  426. player_node.create_sound("Gun_cock", player_node.camera.global_transform.origin)
  427. Now when the player reloads, we'll play the ``Gun_cock`` sound.
  428. Final notes
  429. -----------
  430. .. image:: img/PartThreeFinished.png
  431. Now you have weapons with limited ammo that play sounds when you fire them!
  432. At this point, we have all the basics of an FPS game working.
  433. There are still a few things that would be nice to add, and we're going to add them in the next three parts!
  434. For example, right now we have no way to add ammo to our spares, so we'll eventually run out. Also, we don't
  435. have anything to shoot at outside of the :ref:`RigidBody <class_RigidBody>` nodes.
  436. In :ref:`doc_fps_tutorial_part_four` we'll add some targets to shoot at, along with some health and ammo pick ups!
  437. We're also going to add joypad support, so we can play with wired Xbox 360 controllers!
  438. .. warning:: If you ever get lost, be sure to read over the code again!
  439. You can download the finished project for this part here: :download:`Godot_FPS_Part_3.zip <files/Godot_FPS_Part_3.zip>`