part_five.rst 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958
  1. .. _doc_fps_tutorial_part_five:
  2. Part 5
  3. ======
  4. Part Overview
  5. -------------
  6. In this part we're going to add grenades to our player, give our player the ability to grab and throw objects, and add turrets!
  7. .. image:: img/PartFiveFinished.png
  8. .. note:: You are assumed to have finished :ref:`doc_fps_tutorial_part_four` before moving on to this part of the tutorial.
  9. The finished project from :ref:`doc_fps_tutorial_part_four` will be the starting project for part 5
  10. Let's get started!
  11. Adding grenades
  12. ---------------
  13. First, let's give our player some grenades to play with. Open up ``Grenade.tscn``.
  14. There's a few things to note here, the first and foremost being that our grenades are going to use :ref:`RigidBody <class_RigidBody>` nodes.
  15. We're going to use :ref:`RigidBody <class_RigidBody>` nodes for our grenades so they bounce around the world in a somewhat realistic manner.
  16. The second thing to note is ``Blast_Area``. This is a :ref:`Area <class_Area>` node that will represent the blast radius of our grenade.
  17. Finally, the last thing to note is ``Explosion``. This is the :ref:`Particles <class_Particles>` node that will emit an explosion effect when
  18. the grenades explodes. One thing to note here is that we have ``One shot`` enabled. This is so we emit all of our particles at once. We're also emitting in world
  19. coordinates instead of local coordinates, so we have ``Local Coords`` unchecked as well.
  20. .. note:: If you want you can see how the particles are set up by looking through it's ``Process Material`` and ``Draw Passes``.
  21. Let's write the code needed for our grenade. Select ``Grenade`` and make a new script called ``Grenade.gd``. Add the following:
  22. ::
  23. extends RigidBody
  24. const GRENADE_DAMAGE = 60
  25. const GRENADE_TIME = 2
  26. var grenade_timer = 0
  27. const EXPLOSION_WAIT_TIME = 0.48
  28. var explosion_wait_timer = 0
  29. var rigid_shape
  30. var grenade_mesh
  31. var blast_area
  32. var explosion_particles
  33. func _ready():
  34. rigid_shape = $Collision_Shape
  35. grenade_mesh = $Grenade
  36. blast_area = $Blast_Area
  37. explosion_particles = $Explosion
  38. explosion_particles.emitting = false
  39. explosion_particles.one_shot = true
  40. func _process(delta):
  41. if grenade_timer < GRENADE_TIME:
  42. grenade_timer += delta
  43. return
  44. else:
  45. if explosion_wait_timer <= 0:
  46. explosion_particles.emitting = true
  47. grenade_mesh.visible = false
  48. rigid_shape.disabled = true
  49. mode = RigidBody.MODE_STATIC
  50. var bodies = blast_area.get_overlapping_bodies()
  51. for body in bodies:
  52. if body.has_method("bullet_hit"):
  53. body.bullet_hit(GRENADE_DAMAGE, global_transform.origin)
  54. # This would be the perfect place to play a sound!
  55. if explosion_wait_timer < EXPLOSION_WAIT_TIME:
  56. explosion_wait_timer += delta
  57. if explosion_wait_timer >= EXPLOSION_WAIT_TIME:
  58. queue_free()
  59. Let's go over what's happening, starting with the global variables:
  60. * ``GRENADE_DAMAGE``: The amount of damage the grenade causes when it explodes.
  61. * ``GRENADE_TIME``: The amount of time the grenade takes (in seconds) to explode once it's created/thrown.
  62. * ``grenade_timer``: A variable for tracking how long the grenade has been created/thrown.
  63. * ``EXPLOSION_WAIT_TIME``: The amount of time needed (in seconds) to wait before we destroy the grenade scene after the explosion
  64. * ``explosion_wait_timer``: A variable for tracking how much time has passed since the grenade exploded.
  65. * ``rigid_shape``: The :ref:`CollisionShape <class_CollisionShape>` for the grenade's :ref:`RigidBody <class_RigidBody>`.
  66. * ``grenade_mesh``: The :ref:`MeshInstance <class_MeshInstance>` for the grenade.
  67. * ``blast_area``: The blast :ref:`Area <class_Area>` used to damage things when the grenade explodes.
  68. * ``explosion_particles``: The :ref:`Particles <class_Particles>` that play when the grenade explodes.
  69. Notice how ``EXPLOSION_WAIT_TIME`` is a rather strange number (``0.48``). This is because we want ``EXPLOSION_WAIT_TIME`` to be the length of time
  70. the particles are emitting, so when the particles are done we destroy/free the grenade. We calculate ``EXPLOSION_WAIT_TIME`` by taking the particle's life time
  71. and dividing it by the particle's speed scale. This gets us the exact time the explosion particles will last.
  72. ______
  73. Now let's turn our attention to ``_ready``.
  74. First we get all of the nodes we'll need and assign them to the proper global variables.
  75. We need to get the :ref:`CollisionShape <class_CollisionShape>` and :ref:`MeshInstance <class_MeshInstance>` because similarly to the target in :ref:`doc_fps_tutorial_part_four`,
  76. we will be hiding the grenade's mesh and disabling the collision shape when the grenade explodes.
  77. The reason we need to get the blast :ref:`Area <class_Area>` is so we can damage everything inside it when it explodes. We'll be using code similar to the knife
  78. weapon in our player. We need the :ref:`Particles <class_Particles>` so we can emit them when we explode.
  79. After we get all of the nodes and assign them to their global variables, we then make sure the explosion particles are not emitting, and that they are set to
  80. emit in one shot.
  81. ______
  82. Now let's look at ``_process``.
  83. First we check to see if the ``grenade_timer`` is less than ``GRENADE_TIMER``. If it is, we add ``delta`` and return. This is so we have to wait ``GRENADE_TIME`` seconds,
  84. allowing our :ref:`RigidBody <class_RigidBody>` to move around.
  85. If ``grenade_timer`` is at ``GRENADE_TIMER`` or higher, we then need to check if we waited long enough and need to explode. We do this by checking to see
  86. if ``explosion_wait_timer`` is equal to ``0`` or less. Since we will be adding ``delta`` to ``explosion_wait_timer`` right after, whatever code under the check
  87. will only be called once, right when we've waited long enough and need to explode.
  88. If we've waited long enough to explode, we first tell the ``explosion_particles`` to emit. Then we make ``grenade_mesh`` invisible, and disable ``rigid_shape``, effectively
  89. hiding our grenade.
  90. We then set the :ref:`RigidBody <class_RigidBody>`'s mode to ``MODE_STATIC`` so the grenade does not move.
  91. Then we get all of the bodies in ``blast_area``, check to see if they have the ``bullet_hit`` method/function, and if they do we call it and pass in ``GRENADE_DAMAGE`` and
  92. the grenade's position.
  93. We then check to see if ``explosion_wait_timer`` is less than ``EXPLOSION_WAIT_TIME``. If it is, we add ``delta`` to ``explosion_wait_time``.
  94. Next we check to see if ``explosion_wait_timer`` is more than or equal to ``EXPLOSTION_WAIT_TIME``. Because we added ``delta``, this will only be called once.
  95. If ``explosion_wait_timer`` is more or equal to ``EXPLOSION_WAIT_TIME``, we've waited long enough to let the :ref:`Particles <class_Particles>` play and can free/destroy ourselves.
  96. ______
  97. Let's quickly get the sticky grenade set up too. Open up ``Sticky_Grenade.tscn``.
  98. ``Sticky_Grenade.tscn`` is almost identical to ``Grenade.tscn``, with one small addition. We now have a second
  99. :ref:`Area <class_Area>`, called ``Sticky_Area``. We'll be using ``Stick_Area`` to detect when we've collided with
  100. the environment and need to stick to something.
  101. Select ``Sticky_Grenade`` and make a new script called ``Sticky_Grenade.gd``. Add the following:
  102. ::
  103. extends RigidBody
  104. const GRENADE_DAMAGE = 40
  105. const GRENADE_TIME = 3
  106. var grenade_timer = 0
  107. const EXPLOSION_WAIT_TIME = 0.48
  108. var explosion_wait_timer = 0
  109. var attached = false
  110. var attach_point = null
  111. var rigid_shape
  112. var grenade_mesh
  113. var blast_area
  114. var explosion_particles
  115. var player_body
  116. func _ready():
  117. rigid_shape = $Collision_Shape
  118. grenade_mesh = $Sticky_Grenade
  119. blast_area = $Blast_Area
  120. explosion_particles = $Explosion
  121. explosion_particles.emitting = false
  122. explosion_particles.one_shot = true
  123. $Sticky_Area.connect("body_entered", self, "collided_with_body")
  124. func collided_with_body(body):
  125. if body == self:
  126. return
  127. if player_body != null:
  128. if body == player_body:
  129. return
  130. if attached == false:
  131. attached = true
  132. attach_point = Spatial.new()
  133. body.add_child(attach_point)
  134. attach_point.global_transform.origin = global_transform.origin
  135. rigid_shape.disabled = true
  136. mode = RigidBody.MODE_STATIC
  137. func _process(delta):
  138. if attached == true:
  139. if attach_point != null:
  140. global_transform.origin = attach_point.global_transform.origin
  141. if grenade_timer < GRENADE_TIME:
  142. grenade_timer += delta
  143. return
  144. else:
  145. if explosion_wait_timer <= 0:
  146. explosion_particles.emitting = true
  147. grenade_mesh.visible = false
  148. rigid_shape.disabled = true
  149. mode = RigidBody.MODE_STATIC
  150. var bodies = blast_area.get_overlapping_bodies()
  151. for body in bodies:
  152. if body.has_method("bullet_hit"):
  153. body.bullet_hit(GRENADE_DAMAGE, global_transform.origin)
  154. # This would be the perfect place to play a sound!
  155. if explosion_wait_timer < EXPLOSION_WAIT_TIME:
  156. explosion_wait_timer += delta
  157. if explosion_wait_timer >= EXPLOSION_WAIT_TIME:
  158. if attach_point != null:
  159. attach_point.queue_free()
  160. queue_free()
  161. The code above is almost identical to the code for ``Grenade.gd``, so let's go over what's changed.
  162. First, we have a few more global variables:
  163. * ``attached``: A variable for tracking whether or not we've attached to a :ref:`PhysicsBody <class_PhysicsBody>`.
  164. * ``attach_point``: A variable to hold a :ref:`Spatial <class_Spatial>` that will be at the position we collided at.
  165. * ``player_body``: The player's :ref:`KinematicBody <class_KinematicBody>`.
  166. These additions are so we can stick to any :ref:`PhysicsBody <class_PhysicsBody>` we happen to hit. We also now
  167. need the player's :ref:`KinematicBody <class_KinematicBody>` so we don't stick to the player that threw this grenade.
  168. ______
  169. Now let's look at the small change in ``_ready``. In ``_ready`` we've added a line of code so when any body enters ``Stick_Area``,
  170. the ``collided_with_body`` function is called.
  171. ______
  172. Next let's take a look at ``collided_with_body``.
  173. First we make sure we're not colliding with ourself. Because our :ref:`Area <class_Area>` does not know it's attached to the grenade's :ref:`RigidBody <class_RigidBody>`,
  174. we need to make sure we're not going to stick to ourself. If we have collided with ourself, we ignore it by returning.
  175. We then check to see if we have something assigned to ``player_body``, and if the body we collided with is the player that threw this grenade.
  176. If the body we've collided with is indeed ``player_body``, we ignore it by returning.
  177. Next we check if we are attached already or not.
  178. If we are not attached, we then set ``attached`` to true so we know we've attached to something.
  179. We then make a new :ref:`Spatial <class_Spatial>` node, and make it a child of the body we collided with. We then set the :ref:`Spatial <class_Spatial>`'s position
  180. to our current position.
  181. .. note:: Because we've added the :ref:`Spatial <class_Spatial>` as a child of the body we've collided with, it will follow along with said body. We can then use this
  182. :ref:`Spatial <class_Spatial>` to set our position, so we're always at the same position relative to the body we collided with.
  183. We then disable ``rigid_shape`` so we're not constantly moving whatever body we've collided with. Finally, we set our mode to ``MODE_STATIC`` so the grenade does not move.
  184. ______
  185. Finally, lets go over the few changes in ``_process``.
  186. Now we're checking to see if we are attached right at the top of ``_process``.
  187. If we are attached, we then make sure the attached point is not equal to ``null``.
  188. If the attached point is not equal to ``null``, we set our global position (using our global :ref:`Transform <class_Transform>`'s origin) to the global position of
  189. the :ref:`Spatial <class_Spatial>` assigned to ``attach_point`` (using its global :ref:`Transform <class_Transform>`'s origin).
  190. The only other change is now before we free/destroy the grenade, we check to see if we have an attached point. If we do, we also call ``queue_free`` on it, so it's
  191. also freed/destroyed.
  192. Adding grenades to the player
  193. -----------------------------
  194. Now we need to add some code to ``Player.gd`` so we can use our grenades.
  195. First, open up ``Player.tscn`` and expand the node tree until you get to ``Rotation_Helper``. Notice how in
  196. ``Rotation_Helper`` we have a node called ``Grenade_Toss_Pos``. This is where we will be spawning the grenades.
  197. Also notice how it's slightly rotated on the ``X`` axis, so it's not pointing straight, but rather slightly up. By changing
  198. the rotation of ``Grenade_Toss_Pos``, you can change the angle the grenades are tossed at.
  199. Okay, now lets start making the grenades work with our player. Add the following global variables to ``Player.gd``:
  200. ::
  201. var grenade_amounts = {"Grenade":2, "Sticky Grenade":2}
  202. var current_grenade = "Grenade"
  203. var grenade_scene = preload("res://Grenade.tscn")
  204. var sticky_grenade_scene = preload("res://Sticky_Grenade.tscn")
  205. const GRENADE_THROW_FORCE = 50
  206. * ``grenade_amounts``: The amount of grenades we are currently carrying for each type of grenade.
  207. * ``current_grenade``: The name of the grenade type we're currently using.
  208. * ``grenade_scene``: The grenade scene we worked on earlier.
  209. * ``sticky_grenade_scene``: The sticky grenade scene we worked on earlier.
  210. * ``GRENADE_THROW_FORCE``: The force at which we throw the grenade at.
  211. Most of these variables are similar to how we have out weapons set up.
  212. .. tip:: While it's possible to make a more modular grenade system, I found it was not worth the additional complexity for just two grenades.
  213. If you were going to make a more complex FPS with more grenades, you'd likely want to make a system for grenades similar to how we have the weapons set up.
  214. ______
  215. Now we need to add some code in ``_process_input`` Add the following to ``_process_input``:
  216. ::
  217. # ----------------------------------
  218. # Changing and throwing grenades
  219. if Input.is_action_just_pressed("change_grenade"):
  220. if current_grenade == "Grenade":
  221. current_grenade = "Sticky Grenade"
  222. elif current_grenade == "Sticky Grenade":
  223. current_grenade = "Grenade"
  224. if Input.is_action_just_pressed("fire_grenade"):
  225. if grenade_amounts[current_grenade] > 0:
  226. grenade_amounts[current_grenade] -= 1
  227. var grenade_clone
  228. if (current_grenade == "Grenade"):
  229. grenade_clone = grenade_scene.instance()
  230. elif (current_grenade == "Sticky Grenade"):
  231. grenade_clone = sticky_grenade_scene.instance()
  232. # Sticky grenades will stick to the player if we do not pass ourselves
  233. grenade_clone.player_body = self
  234. get_tree().root.add_child(grenade_clone)
  235. grenade_clone.global_transform = $Rotation_Helper/Grenade_Toss_Pos.global_transform
  236. grenade_clone.apply_impulse(Vector3(0,0,0), grenade_clone.global_transform.basis.z * GRENADE_THROW_FORCE)
  237. # ----------------------------------
  238. Let's go over what's happening here.
  239. First, we check to see if the ``change_grenade`` action has just been pressed. If it has, we then check to see which grenade we
  240. are currently using. Based on the name of the grenade we're currently using, we change ``current_grenade`` to the opposite grenade name.
  241. Next we check to see if the ``fire_grenade`` action has just been pressed. If it has, we then check to see if we have more than ``0`` grenades for the
  242. current grenade we have selected.
  243. If we have more than ``0`` grenades, we then remove one from the grenade amounts for the current grenade.
  244. Then, based on the grenade we're currently using we instance the proper grenade scene and assign it to ``grenade_clone``.
  245. Next we add ``grenade_clone`` as a child of the node at the root, and set its global :ref:`Transform <class_Transform>` to
  246. ``Grenade_Toss_Pos``'s global :ref:`Transform <class_Transform>`. Finally, we apply an impulse to the grenade so that it is launched forward, relative
  247. to the ``Z`` directional vector of ``grenade_clone``'s.
  248. ______
  249. Now we can use both types of grenades, but there's a few things we should probably add before we move on to adding the other things.
  250. We still need a way to see how many grenades we have left, and we should probably have a way to get more grenades when we pick up ammo.
  251. First, let's change some of the code in ``Player.gd`` so we can see how many grenades we have left. Change ``process_UI`` to the following:
  252. ::
  253. func process_UI(delta):
  254. if current_weapon_name == "UNARMED" or current_weapon_name == "KNIFE":
  255. # First line: Health, second line: Grenades
  256. UI_status_label.text = "HEALTH: " + str(health) + \
  257. "\n" + current_grenade + ":" + str(grenade_amounts[current_grenade])
  258. else:
  259. var current_weapon = weapons[current_weapon_name]
  260. # First line: Health, second line: weapon and ammo, third line: grenades
  261. UI_status_label.text = "HEALTH: " + str(health) + \
  262. "\nAMMO:" + str(current_weapon.ammo_in_weapon) + "/" + str(current_weapon.spare_ammo) + \
  263. "\n" + current_grenade + ":" + str(grenade_amounts[current_grenade])
  264. Now we'll show how many grenades we have left in our UI.
  265. While we're still in ``Player.gd``, let's add a function to add grenades. Add the following function to ``Player.gd``:
  266. ::
  267. func add_grenade(additional_grenade):
  268. grenade_amounts[current_grenade] += additional_grenade
  269. grenade_amounts[current_grenade] = clamp(grenade_amounts[current_grenade], 0, 4)
  270. Now we can add a grenade using ``add_grenade``, and it will automatically be clamped to a maximum of ``4`` grenades.
  271. .. tip:: You can change the ``4`` to a constant if you want. You'd need to make a new global constant, something like ``MAX_GRENADES``, and
  272. then change the clamp from ``clamp(grenade_amounts[current_grenade], 0, 4)`` to ``clamp(grenade_amounts[current_grenade], 0, MAX_GRENADES)``
  273. If you do not want to limit how many grenades you can carry, remove the line that clamps the grenades altogether!
  274. Now we have a function to add grenades, let's open up ``AmmoPickup.gd`` and use it!
  275. Open up ``AmmoPickup.gd`` and go to the ``trigger_body_entered`` function. Change it to the following:
  276. ::
  277. func trigger_body_entered(body):
  278. if body.has_method("add_ammo"):
  279. body.add_ammo(AMMO_AMOUNTS[kit_size])
  280. respawn_timer = RESPAWN_TIME
  281. kit_size_change_values(kit_size, false)
  282. if body.has_method("add_grenade"):
  283. body.add_grenade(GRENADE_AMOUNTS[kit_size])
  284. respawn_timer = RESPAWN_TIME
  285. kit_size_change_values(kit_size, false)
  286. Now we're also checking to see if the body has the ``add_grenade`` function. If it does, we call it like we call ``add_ammo``.
  287. You may have noticed we're using a new constant we haven't defined yet, ``GRENADE_AMOUNTS``. Let's add it! Add the following global variable
  288. to ``AmmoPickup.gd`` with the other global variables:
  289. ::
  290. const GRENADE_AMOUNTS = [2, 0]
  291. * ``GRENADE_AMOUNTS``: The amount of grenades each pick up in each size contains.
  292. Notice how the second element in ``GRENADE_AMOUNTS`` is ``0``. This is so the small ammo pick up does not give our player
  293. any additional grenades.
  294. ______
  295. Now you should be able to throw grenades now! Go give it a try!
  296. Adding the ability to grab and throw RigidBody nodes to the player
  297. ------------------------------------------------------------------
  298. Next let's give our player the ability to pick up and throw :ref:`RigidBody <class_RigidBody>` nodes.
  299. Open up ``Player.gd`` and add the following global variables:
  300. ::
  301. var grabbed_object = null
  302. const OBJECT_THROW_FORCE = 120
  303. const OBJECT_GRAB_DISTANCE = 7
  304. const OBJECT_GRAB_RAY_DISTANCE = 10
  305. * ``grabbed_object``: A variable to hold the grabbed :ref:`RigidBody <class_RigidBody>` node.
  306. * ``OBJECT_THROW_FORCE``: The force we throw the grabbed object at.
  307. * ``OBJECT_GRAB_DISTANCE``: The distance away from the camera we hold the grabbed object at.
  308. * ``OBJECT_GRAB_RAY_DISTANCE``: The distance the :ref:`Raycast <class_Raycast>` goes. This is our grab distance.
  309. With that done, all we need to do is add some code to ``process_input``:
  310. ::
  311. # ----------------------------------
  312. # Grabbing and throwing objects
  313. if Input.is_action_just_pressed("fire") and current_weapon_name == "UNARMED":
  314. if grabbed_object == null:
  315. var state = get_world().direct_space_state
  316. var center_position = get_viewport().size/2
  317. var ray_from = camera.project_ray_origin(center_position)
  318. var ray_to = ray_from + camera.project_ray_normal(center_position) * OBJECT_GRAB_RAY_DISTANCE
  319. var ray_result = state.intersect_ray(ray_from, ray_to, [self, $Rotation_Helper/Gun_Fire_Points/Knife_Point/Area])
  320. if ray_result:
  321. if ray_result["collider"] is RigidBody:
  322. grabbed_object = ray_result["collider"]
  323. grabbed_object.mode = RigidBody.MODE_STATIC
  324. grabbed_object.collision_layer = 0
  325. grabbed_object.collision_mask = 0
  326. else:
  327. grabbed_object.mode = RigidBody.MODE_RIGID
  328. grabbed_object.apply_impulse(Vector3(0,0,0), -camera.global_transform.basis.z.normalized() * OBJECT_THROW_FORCE)
  329. grabbed_object.collision_layer = 1
  330. grabbed_object.collision_mask = 1
  331. grabbed_object = null
  332. if grabbed_object != null:
  333. grabbed_object.global_transform.origin = camera.global_transform.origin + (-camera.global_transform.basis.z.normalized() * OBJECT_GRAB_DISTANCE)
  334. # ----------------------------------
  335. Let's go over what's happening.
  336. First we check to see if the action pressed is the ``fire`` action, and that we are using the ``UNARMED`` weapon.
  337. This is because we only want to be able to pick up and throw objects when we're not using any weapons. This is a design choice,
  338. but I feel it gives ``UNARMED`` a use.
  339. Next we check to see whether or not ``grabbed_object`` is ``null``.
  340. ______
  341. If ``grabbed_object`` is ``null``, we want to see if we can pick up a :ref:`RigidBody <class_RigidBody>`.
  342. We first get the direct space state from the current :ref:`World <class_World>`. This is so we can cast a ray entirely from code, instead of having to
  343. use a :ref:`Raycast <class_Raycast>` node.
  344. .. note:: see :ref:`Ray-casting <doc_ray-casting>` for more information on raycasting in Godot.
  345. Then we get the center of the screen by dividing the current :ref:`Viewport <class_Viewport>` size in half. We then get the ray's origin point and end point using
  346. ``project_ray_origin`` and ``project_ray_normal`` from the camera. If you want to know more about how these functions work, see :ref:`Ray-casting <doc_ray-casting>`.
  347. Next we send our ray into the space state and see if we get a result. We add ourselves and the knife's :ref:`Area <class_Area>` as two exceptions so we cannot carry
  348. ourselves or the knife's collision area.
  349. Then we check to see if we got a result back. If we have, we then see if the collider the ray collided with is a :ref:`RigidBody <class_RigidBody>`.
  350. If the ray collided with a :ref:`RigidBody <class_RigidBody>`, we set ``grabbed_object`` to the collider the ray collided with. We then set the mode on
  351. the :ref:`RigidBody <class_RigidBody>` we collided with to ``MODE_STATIC`` so it's not moved.
  352. Finally, we set its collision layer and collision mask to ``0``. This will make it have no collision layer or mask, which will means it will not be able to collide with anything.
  353. ______
  354. If ``grabbed_object`` is not ``null``, then we need to throw the :ref:`RigidBody <class_RigidBody>` we're holding.
  355. We first set the :ref:`RigidBody <class_RigidBody>` we holding mode to ``MODE_RIGID``.
  356. .. note:: This is making a rather large assumption that the all rigid bodies will be using ``MODE_RIGID``. While that is the case for this tutorial series,
  357. that may not be the case in other projects.
  358. If you have :ref:`RigidBody <class_RigidBody>`'s with different modes, you may need to store the mode of the :ref:`RigidBody <class_RigidBody>` you
  359. have picked up into a global variable so you can change it back to the mode it was in before you picked it up.
  360. Then we apply an impulse to send it flying forward. We send it flying in the direction the camera is facing, at ``OBJECT_THROW_FORCE`` force.
  361. We then set the grabbed :ref:`RigidBody <class_RigidBody>`'s collision layer and mask to ``1``, so it can collide with anything on layer ``1`` again.
  362. .. note:: This is, once again, making a rather large assumption that all rigid bodies will be only on collision layer ``1``, and all collision masks will be on layer ``1``.
  363. If you are using this script in other projects, you may need to store the collision layer/mask of the :ref:`RigidBody <class_RigidBody>` before you change them to ``0``.
  364. Finally, we set ``grabbed_object`` to ``null`` since we have successfully thrown the held object.
  365. ______
  366. The last thing we do is check to see whether or not ``grabbed_object`` is equal to ``null``, outside of the grabbing/throwing code.
  367. .. note:: While technically not input related, it's easy enough to place the code moving the grabbed object here
  368. because it's only two lines, and then all of the grabbing/throwing code is in one place
  369. If we are holding an object, we set its global position to the camera's position plus ``OBJECT_GRAB_DISTANCE`` in the direction the camera is facing.
  370. ______
  371. Before we test this, we need to change something in ``_physics_process``. While we're holding an object, we don't
  372. want to be able to change weapons or reload, so change ``_physics_process`` to the following:
  373. ::
  374. func _physics_process(delta):
  375. process_input(delta)
  376. process_view_input(delta)
  377. process_movement(delta)
  378. if grabbed_object == null:
  379. process_changing_weapons(delta)
  380. process_reloading(delta)
  381. # Process the UI
  382. process_UI(delta)
  383. Now we cannot change weapons or reload while holding an object.
  384. Now you can grab and throw RigidBody nodes while in a ``UNARMED`` state! Go give it a try!
  385. Adding a turret
  386. ---------------
  387. Next, let's make a turret to shoot our player!
  388. Open up ``Turret.tscn``. Expand ``Turret`` if it's not already expanded.
  389. Notice how our turret is broken up into several parts. We have a ``Base``, ``Head``, ``Vision_Area``, and a ``Smoke`` :ref:`Particles <class_Particles>`.
  390. Open up ``Base`` and you'll find it's a :ref:`StaticBody <class_StaticBody>` and a mesh. Open up ``Head`` and you'll find there's several meshes,
  391. a :ref:`StaticBody <class_StaticBody>` and a :ref:`Raycast <class_Raycast>` node.
  392. One thing to note with the ``Head`` is that the raycast will be where our bullets will fire from if we are using raycasting. We also have two meshes called
  393. ``Flash`` and ``Flash_2``. These will be the muzzle flash that briefly shows when the turret fires.
  394. ``Vision_Area`` is a :ref:`Area <class_Area>` we'll use as the turret's ability to see. When something enters ``Vision_Area``, we'll assume the turret can see it.
  395. ``Smoke`` is a :ref:`Particles <class_Particles>` node that will play when the turret is destroyed and repairing.
  396. ______
  397. Now that we've looked at how the scene is set up, lets start writting the code for the turret. Select ``Turret`` and create a new script called ``Turret.gd``.
  398. Add the following to ``Turret.gd``:
  399. ::
  400. extends Spatial
  401. export (bool) var use_raycast = false
  402. const TURRET_DAMAGE_BULLET = 20
  403. const TURRET_DAMAGE_RAYCAST = 5
  404. const FLASH_TIME = 0.1
  405. var flash_timer = 0
  406. const FIRE_TIME = 0.8
  407. var fire_timer = 0
  408. var node_turret_head = null
  409. var node_raycast = null
  410. var node_flash_one = null
  411. var node_flash_two = null
  412. var ammo_in_turret = 20
  413. const AMMO_IN_FULL_TURRET = 20
  414. const AMMO_RELOAD_TIME = 4
  415. var ammo_reload_timer = 0
  416. var current_target = null
  417. var is_active = false
  418. const PLAYER_HEIGHT = 3
  419. var smoke_particles
  420. var turret_health = 60
  421. const MAX_TURRET_HEALTH = 60
  422. const DESTROYED_TIME = 20
  423. var destroyed_timer = 0
  424. var bullet_scene = preload("Bullet_Scene.tscn")
  425. func _ready():
  426. $Vision_Area.connect("body_entered", self, "body_entered_vision")
  427. $Vision_Area.connect("body_exited", self, "body_exited_vision")
  428. node_turret_head = $Head
  429. node_raycast = $Head/Ray_Cast
  430. node_flash_one = $Head/Flash
  431. node_flash_two = $Head/Flash_2
  432. node_raycast.add_exception(self)
  433. node_raycast.add_exception($Base/Static_Body)
  434. node_raycast.add_exception($Head/Static_Body)
  435. node_raycast.add_exception($Vision_Area)
  436. node_flash_one.visible = false
  437. node_flash_two.visible = false
  438. smoke_particles = $Smoke
  439. smoke_particles.emitting = false
  440. turret_health = MAX_TURRET_HEALTH
  441. func _physics_process(delta):
  442. if is_active == true:
  443. if flash_timer > 0:
  444. flash_timer -= delta
  445. if flash_timer <= 0:
  446. node_flash_one.visible = false
  447. node_flash_two.visible = false
  448. if current_target != null:
  449. node_turret_head.look_at(current_target.global_transform.origin + Vector3(0, PLAYER_HEIGHT, 0), Vector3(0, 1, 0))
  450. if turret_health > 0:
  451. if ammo_in_turret > 0:
  452. if fire_timer > 0:
  453. fire_timer -= delta
  454. else:
  455. fire_bullet()
  456. else:
  457. if ammo_reload_timer > 0:
  458. ammo_reload_timer -= delta
  459. else:
  460. ammo_in_turret = AMMO_IN_FULL_TURRET
  461. if turret_health <= 0:
  462. if destroyed_timer > 0:
  463. destroyed_timer -= delta
  464. else:
  465. turret_health = MAX_TURRET_HEALTH
  466. smoke_particles.emitting = false
  467. func fire_bullet():
  468. if use_raycast == false:
  469. var clone = bullet_scene.instance()
  470. var scene_root = get_tree().root.get_children()[0]
  471. scene_root.add_child(clone)
  472. clone.global_transform = $Head/Barrel_End.global_transform
  473. clone.scale = Vector3(8, 8, 8)
  474. clone.BULLET_DAMAGE = TURRET_DAMAGE_BULLET
  475. clone.BULLET_SPEED = 60
  476. ammo_in_turret -= 1
  477. else:
  478. node_raycast.look_at(current_target.global_transform.origin + PLAYER_HEIGHT, Vector3(0,1,0))
  479. node_raycast.force_raycast_update()
  480. if node_raycast.is_colliding():
  481. var body = node_raycast.get_collider()
  482. if body.has_method("bullet_hit"):
  483. body.bullet_hit(TURRET_DAMAGE_RAYCAST, node_raycast.get_collision_point())
  484. ammo_in_turret -= 1
  485. node_flash_one.visible = true
  486. node_flash_two.visible = true
  487. flash_timer = FLASH_TIME
  488. fire_timer = FIRE_TIME
  489. if ammo_in_turret <= 0:
  490. ammo_reload_timer = AMMO_RELOAD_TIME
  491. func body_entered_vision(body):
  492. if current_target == null:
  493. if body is KinematicBody:
  494. current_target = body
  495. is_active = true
  496. func body_exited_vision(body):
  497. if current_target != null:
  498. if body == current_target:
  499. current_target = null
  500. is_active = false
  501. flash_timer = 0
  502. fire_timer = 0
  503. node_flash_one.visible = false
  504. node_flash_two.visible = false
  505. func bullet_hit(damage, bullet_hit_pos):
  506. turret_health -= damage
  507. if turret_health <= 0:
  508. smoke_particles.emitting = true
  509. destroyed_timer = DESTROYED_TIME
  510. This is quite a bit of code, so let's break it down function by function. Let's first look at the global variables:
  511. * ``use_raycast``: A exported boolean so we can change whether the turret uses objects or raycasting for bullets.
  512. * ``TURRET_DAMAGE_BULLET``: The amount of damage a single bullet scene does.
  513. * ``TURRET_DAMAGE_RAYCAST``: The amount of damage a single :ref:`Raycast <class_Raycast>` bullet does.
  514. * ``FLASH_TIME``: The amount of time (in seconds) the muzzle flash meshes are visible.
  515. * ``flash_timer``: A variable for tracking how long the muzzle flash meshes have been visible.
  516. * ``FIRE_TIME``: The amount of time (in seconds) needed to fire a bullet.
  517. * ``fire_timer``: A variable for tracking how much time has passed since the turret last fired.
  518. * ``node_turret_head``: A variable to hold the ``Head`` node.
  519. * ``node_raycast``: A variable to hold the :ref:`Raycast <class_Raycast>` node attached to the turret's head.
  520. * ``node_flash_one``: A variable to hold the first muzzle flash :ref:`MeshInstance <class_MeshInstance>`.
  521. * ``node_flash_two``: A variable to hold the second muzzle flash :ref:`MeshInstance <class_MeshInstance>`.
  522. * ``ammo_in_turret``: The amount of ammo currently in the turret.
  523. * ``AMMO_IN_FULL_TURRET``: The amount of ammo in a full turret.
  524. * ``AMMO_RELOAD_TIME``: The amount of time it takes the turret to reload.
  525. * ``ammo_reload_timer``: A variable for tracking how long the turret has been reloading.
  526. * ``current_target``: The turret's current target.
  527. * ``is_active``: A variable for tracking whether the turret is able to fire at the target.
  528. * ``PLAYER_HEIGHT``: The amount of height we're adding to the target so we're not shooting at its feet.
  529. * ``smoke_particles``: A variable to hold the smoke particles node.
  530. * ``turret_health``: The amount of health the turret currently has.
  531. * ``MAX_TURRET_HEALTH``: The amount of health a fully healed turret has.
  532. * ``DESTROYED_TIME``: The amount of time (in seconds) it takes for a destroyed turret to repair itself.
  533. * ``destroyed_timer``: A variable for tracking the amount of time a turret has been destroyed.
  534. * ``bullet_scene``: The bullet scene the turret fires (same scene as the player's pistol)
  535. Phew, that's quite a few global variables!
  536. ______
  537. Let's go through ``_ready`` next.
  538. First we get the vision area and connect the ``body_entered`` and ``body_exited`` signals to ``body_entered_vision`` and ``body_exited_vision`` respectively.
  539. We then get all of the nodes and assign them to their respective variables.
  540. Next add some exceptions to the :ref:`Raycast <class_Raycast>` so the turret cannot hurt itself.
  541. Then we make both flash meshes invisible to start, since we're not going to be firing during ``_ready``.
  542. We then get the smoke particles node and assign it to the ``smoke_particles`` node. We also set ``emitting`` to ``false`` to assure it's
  543. not emitting until the turret is broken.
  544. Finally, we set the turret's health to ``MAX_TURRET_HEALTH`` so it starts at full health.
  545. ______
  546. Now let's go through ``_physics_process``.
  547. First we check to see if the turret is active. If the turret is active we want to process the firing code.
  548. Next we check to see if ``flash_timer`` is more than zero, meaning the flash meshes are visible, we want to remove
  549. delta from ``flash_timer``. If ``flash_timer`` gets to zero or less after we've subtracted ``delta``, we want to hide
  550. both of the flash meshes.
  551. Next we check to see if we have a target or not. If we have a target, we make the turret head look at it, adding ``PLAYER_HEIGHT`` so we're not
  552. aiming at the player's feet.
  553. We then check to see if the turret's health is more than zero. If it is, we then check to see if there is ammo in the turret.
  554. If there is ammo in the turret, we then check to see if ``fire_timer`` is more than zero. If ``fire_timer`` is more than zero, we cannot fire and need to
  555. remove ``delta`` from ``fire_timer``. If ``fire_timer`` is equal to or less than zero, we want to fire a bullet, so we call the ``fire_bullet`` function.
  556. If there is not any ammo in the turret, we check to see if ``ammo_reload_timer`` is more than zero. If ``ammo_reload_timer`` is more than zero,
  557. we subtract ``delta`` from ``ammo_reload_timer``. If ``ammo_reload_timer`` is equal to or less than zero, we set ``ammo_in_turret`` to ``AMMO_IN_FULL_TURRET`` because
  558. we've waited long enough to refill the turret.
  559. Next we check to see if the turret's health is less than or equal to ``0``, outside of whether we're active or not. If the turret's health is zero or less, we then
  560. check to see if ``destroyed_timer`` is more than zero. If destroyed timer is more than zero, we subtract ``delta`` from ``destroyed_timer``.
  561. If ``destyored_timer`` is less than or equal to zero, we set ``turret_health`` to ``MAX_TURRET_HEALTH`` and stop emitting smoke particles by setting ``smoke_particles.emitting`` to
  562. ``false``.
  563. ______
  564. Next let's go through ``fire_bullet``.
  565. First we check to see whether we're using a raycast or not.
  566. The code for the using a raycast is almost entirely the same as the code in the rifle from :ref:`doc_fps_tutorial_part_two`, so
  567. I'm only going to go over it briefly.
  568. We first make the raycast look at the target, assuring we'll hit the target. We then force the raycast to update so we get a frame
  569. perfect collision check. We then check if the raycast collided with anything. If the raycast has collided with something, we then check
  570. to see if the collided body has the ``bullet_hit`` function. If it does, we call it and pass in the damage a single raycast bullet does. We then remove
  571. ``1`` from ``ammo_in_turret``.
  572. If we are not using a raycast, we spawn a bullet object instead. This code is almost entirely the same as the code in the pistol from :ref:`doc_fps_tutorial_part_two`, so
  573. like with the raycast code, I'm only going to go over it briefly.
  574. We first make a bullet clone and assign it to ``clone``. We then add that as a child of the root node. We set it's global transform to
  575. the barrel end, scale it up since it's too small, and set it's damage and speed using the turret's constant global variables. We then remove ``1`` from
  576. ``ammo_in_turret``.
  577. Then, regardless of which bullet method we used, we make both of the muzzle flash meshes visible. We set ``flash_timer`` and ``fire_timer`` to
  578. to ``FLASH_TIME`` and ``FIRE_TIME`` respectively. We then check to see if we used the last bullet in the turret. If we have used the last bullet,
  579. we set ``ammo_reload_timer`` to ``AMMO_RELOAD_TIME``.
  580. ______
  581. Let's look at ``body_entered_vision`` next, and thankfully it's rather short.
  582. We first check to see if we currently have a target by checking to see if ``current_target`` is equal to ``null``.
  583. If we do not have a target, we then check to see if the body that just entered the vision :ref:`Area <class_Area>` is a :ref:`KinematicBody <class_KinematicBody>`
  584. ..note:: We're assuming the turret only should fire at :ref:`KinematicBody <class_KinematicBody>` nodes, since that's what our player(s) are using.
  585. If the body that just the vision :ref:`Area <class_Area>` is a :ref:`KinematicBody <class_KinematicBody>`, we set ``current_target`` to the body, and set ``is_active`` to
  586. ``true``.
  587. ______
  588. Now let's look at ``body_exited_vision``.
  589. First we check to see if we have a target. If we have a target, we then check to see if the body that has just left our vision area
  590. is our target.
  591. If the body that just left the area is the current target, we set ``current_target`` to ``null``, set ``is_active`` to ``false``, and reset
  592. all of the variables related to firing the turret, since we no longer have a target to fire at.
  593. ______
  594. Finally, let's look at ``bullet_hit``.
  595. We first remove however much damage we have received from the turret's health.
  596. Then we check to see if we've been destroyed. If we have, we start the smoke particles emitting and set ``destroyed_timer`` to ``DESTROYED_TIME`` so we
  597. have to wait to repair the turret.
  598. ______
  599. Phew, with all of that done and coded we only have one last thing to do before our turrets are ready for use. Open up ``Turret.tscn`` if it's not already open and
  600. select one of the :ref:`StaticBody <class_StaticBody>` nodes from either ``Body`` or ``Head``. Create a new script called ``TurretBodies.gd`` and attach it to whichever
  601. :ref:`StaticBody <class_StaticBody>` you have selected.
  602. Add the following code to ``TurretBodies.gd``:
  603. ::
  604. extends StaticBody
  605. export (NodePath) var path_to_turret_root
  606. func _ready():
  607. pass
  608. func bullet_hit(damage, bullet_hit_pos):
  609. if path_to_turret_root != null:
  610. get_node(path_to_turret_root).bullet_hit(damage, bullet_hit_pos)
  611. All this code does is call ``bullet_hit`` on whatever node ``path_to_turret_root`` leads to. Go back to the editor and assign the :ref:`NodePath <class_NodePath>`
  612. to the ``Turret`` node.
  613. Now select the other :ref:`StaticBody <class_StaticBody>` node (either in ``Body`` or ``Head``) and assign ``TurretBodies.gd`` to it. Once the script is
  614. attached, assign the :ref:`NodePath <class_NodePath>` to the ``Turret`` node.
  615. ______
  616. The last thing we need to do is add a way for the player to be hurt. Since all of our bullets use the ``bullet_hit`` function, we need to add that to our player.
  617. Open ``Player.gd`` and add the following:
  618. ::
  619. func bullet_hit(damage, bullet_hit_pos):
  620. health -= damage
  621. With all that done, you should have fully operational turrets! Go place a few in one/both/all of the scenes and give them a try!
  622. Final notes
  623. -----------
  624. .. image:: img/PartFiveFinished.png
  625. Now you the player can pick up :ref:`RigidBody <class_RigidBody>` nodes and throw grenades. We now also have turrets to fire at our player.
  626. In :ref:`doc_fps_tutorial_part_six`, we're going to add a main menu and pause menu,
  627. add a respawn system for the player, and change/move the sound system so we can use it from any script.
  628. .. warning:: If you ever get lost, be sure to read over the code again!
  629. You can download the finished project for this part here: :download:`Godot_FPS_Part_5.zip <files/Godot_FPS_Part_5.zip>`