part_two.rst 57 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237
  1. .. _doc_fps_tutorial_part_two:
  2. Part 2
  3. ======
  4. Part Overview
  5. -------------
  6. In this part we will be giving our player weapons to play with.
  7. .. image:: img/PartTwoFinished.png
  8. By the end of this part, you will have a player that can fire a pistol,
  9. rifle, and attack using a knife. The player will also now have animations with transitions,
  10. and the weapons will interact with objects in the environment.
  11. .. note:: You are assumed to have finished :ref:`doc_fps_tutorial_part_one` before moving on to this part of the tutorial.
  12. The finished project from :ref:`doc_fps_tutorial_part_one` will be the starting project for part 2
  13. Let's get started!
  14. Making a system to handle animations
  15. ------------------------------------
  16. First we need a way to handle changing animations. Open up ``Player.tscn`` and select the :ref:`AnimationPlayer <class_AnimationPlayer>`
  17. Node (``Player`` -> ``Rotation_Helper`` -> ``Model`` -> ``Animation_Player``).
  18. Create a new script called ``AnimationPlayer_Manager.gd`` and attach that to the :ref:`AnimationPlayer <class_AnimationPlayer>`.
  19. Add the following code to ``AnimationPlayer_Manager.gd``:
  20. ::
  21. extends AnimationPlayer
  22. # Structure -> Animation name :[Connecting Animation states]
  23. var states = {
  24. "Idle_unarmed":["Knife_equip", "Pistol_equip", "Rifle_equip", "Idle_unarmed"],
  25. "Pistol_equip":["Pistol_idle"],
  26. "Pistol_fire":["Pistol_idle"],
  27. "Pistol_idle":["Pistol_fire", "Pistol_reload", "Pistol_unequip", "Pistol_idle"],
  28. "Pistol_reload":["Pistol_idle"],
  29. "Pistol_unequip":["Idle_unarmed"],
  30. "Rifle_equip":["Rifle_idle"],
  31. "Rifle_fire":["Rifle_idle"],
  32. "Rifle_idle":["Rifle_fire", "Rifle_reload", "Rifle_unequip", "Rifle_idle"],
  33. "Rifle_reload":["Rifle_idle"],
  34. "Rifle_unequip":["Idle_unarmed"],
  35. "Knife_equip":["Knife_idle"],
  36. "Knife_fire":["Knife_idle"],
  37. "Knife_idle":["Knife_fire", "Knife_unequip", "Knife_idle"],
  38. "Knife_unequip":["Idle_unarmed"],
  39. }
  40. var animation_speeds = {
  41. "Idle_unarmed":1,
  42. "Pistol_equip":1.4,
  43. "Pistol_fire":1.8,
  44. "Pistol_idle":1,
  45. "Pistol_reload":1,
  46. "Pistol_unequip":1.4,
  47. "Rifle_equip":2,
  48. "Rifle_fire":6,
  49. "Rifle_idle":1,
  50. "Rifle_reload":1.45,
  51. "Rifle_unequip":2,
  52. "Knife_equip":1,
  53. "Knife_fire":1.35,
  54. "Knife_idle":1,
  55. "Knife_unequip":1,
  56. }
  57. var current_state = null
  58. var callback_function = null
  59. func _ready():
  60. set_animation("Idle_unarmed")
  61. connect("animation_finished", self, "animation_ended")
  62. func set_animation(animation_name):
  63. if animation_name == current_state:
  64. print ("AnimationPlayer_Manager.gd -- WARNING: animation is already ", animation_name)
  65. return true
  66. if has_animation(animation_name) == true:
  67. if current_state != null:
  68. var possible_animations = states[current_state]
  69. if animation_name in possible_animations:
  70. current_state = animation_name
  71. play(animation_name, -1, animation_speeds[animation_name])
  72. return true
  73. else:
  74. print ("AnimationPlayer_Manager.gd -- WARNING: Cannot change to ", animation_name, " from ", current_state)
  75. return false
  76. else:
  77. current_state = animation_name
  78. play(animation_name, -1, animation_speeds[animation_name])
  79. return true
  80. return false
  81. func animation_ended(anim_name):
  82. # UNARMED transitions
  83. if current_state == "Idle_unarmed":
  84. pass
  85. # KNIFE transitions
  86. elif current_state == "Knife_equip":
  87. set_animation("Knife_idle")
  88. elif current_state == "Knife_idle":
  89. pass
  90. elif current_state == "Knife_fire":
  91. set_animation("Knife_idle")
  92. elif current_state == "Knife_unequip":
  93. set_animation("Idle_unarmed")
  94. # PISTOL transitions
  95. elif current_state == "Pistol_equip":
  96. set_animation("Pistol_idle")
  97. elif current_state == "Pistol_idle":
  98. pass
  99. elif current_state == "Pistol_fire":
  100. set_animation("Pistol_idle")
  101. elif current_state == "Pistol_unequip":
  102. set_animation("Idle_unarmed")
  103. elif current_state == "Pistol_reload":
  104. set_animation("Pistol_idle")
  105. # RIFLE transitions
  106. elif current_state == "Rifle_equip":
  107. set_animation("Rifle_idle")
  108. elif current_state == "Rifle_idle":
  109. pass;
  110. elif current_state == "Rifle_fire":
  111. set_animation("Rifle_idle")
  112. elif current_state == "Rifle_unequip":
  113. set_animation("Idle_unarmed")
  114. elif current_state == "Rifle_reload":
  115. set_animation("Rifle_idle")
  116. func animation_callback():
  117. if callback_function == null:
  118. print ("AnimationPlayer_Manager.gd -- WARNING: No callback function for the animation to call!")
  119. else:
  120. callback_function.call_func()
  121. Lets go over what this script is doing:
  122. _________
  123. Lets start with this script's global variables:
  124. - ``states``: A dictionary for holding our animation states. (Further explanation below)
  125. - ``animation_speeds``: A dictionary for holding all of the speeds we want to play our animations at.
  126. - ``current_state``: A variable for holding the name of the animation state we are currently in.
  127. - ``callback_function``: A variable for holding the callback function. (Further explanation below)
  128. If you are familiar with state machines, then you may have noticed that ``states`` is structured
  129. like a basic state machine. Here is roughly how ``states`` is set up:
  130. ``states`` is a dictionary with the key being the name of the current state, and the value being
  131. an array holding all of the states we can transition to. For example, if we are in currently in
  132. state ``Idle_unarmed``, we can only transition to ``Knife_equip``, ``Pistol_equip``, ``Rifle_equip``, and
  133. ``Idle_unarmed``.
  134. If we try to transition to a state that is not included in our possible transitions states,
  135. then we get a warning message and the animation does not change. We can also automatically
  136. transition from some states into others, as will be explained further below in ``animation_ended``
  137. .. note:: For the sake of keeping this tutorial simple we are not using a 'proper'
  138. state machine. If you are interested to know more about state machines,
  139. see the following articles:
  140. - (Python example) https://dev.to/karn/building-a-simple-state-machine-in-python
  141. - (C# example) https://www.codeproject.com/Articles/489136/UnderstandingplusandplusImplementingplusStateplusP
  142. - (Wiki article) https://en.wikipedia.org/wiki/Finite-state_machine
  143. ``animation_speeds`` is how fast each animation will play. Some of the animations are a little slow
  144. and in an effort to make everything look smooth, we need to play them at faster speeds.
  145. .. tip:: Notice that all of the firing animations are faster than their normal speed. Remember this for later!
  146. ``current_state`` will hold the name of the animation state we are currently in.
  147. Finally, ``callback_function`` will be a :ref:`FuncRef <class_FuncRef>` passed in by our player for spawning bullets
  148. at the proper frame of animation. A :ref:`FuncRef <class_FuncRef>` allows us to pass in a function as an argument,
  149. effectively allowing us to call a function from another script, which is how we will use it later.
  150. _________
  151. Now lets look at ``_ready``.
  152. First we are setting our animation to ``Idle_unarmed`` using the ``set_animation`` function,
  153. so we for sure start in that animation.
  154. Next we connect the ``animation_finished`` signal to this script and assign it to call ``animation_ended``.
  155. This means whenever an animation is finished, ``animation_ended`` will be called.
  156. _________
  157. Lets look at ``set_animation`` next.
  158. ``set_animation`` sets the animation to the that of the passed in
  159. animation state *if* we can transition to it. In other words, if the animation state we are currently in
  160. has the passed in animation state name in ``states``, then we will change to that animation.
  161. To start we check if the passed in animation is the same as the animation state we are currently in.
  162. If they are the same, then we write a warning to the console and return ``true``.
  163. Next we see if :ref:`AnimationPlayer <class_AnimationPlayer>` has the passed in animation using ``has_animation``. If it does not, we return ``false``.
  164. Then we check if ``current_state`` is set or not. If ``current_state`` is *not* currently set, we
  165. set ``current_state`` to the passed in animation and tell :ref:`AnimationPlayer <class_AnimationPlayer>` to start playing the animation with
  166. a blend time of ``-1`` and at the speed set in ``animation_speeds`` and then we return ``true``.
  167. If we have a state in ``current_state``, then we get all of the possible states we can transition to.
  168. If the animation name is in the list of possible transitions, we set ``current_state`` to the passed
  169. in animation, tell :ref:`AnimationPlayer <class_AnimationPlayer>` to play the animation with a blend time of ``-1`` at the speed set in ``animation_speeds``
  170. and return ``true``.
  171. _________
  172. Now lets look at ``animation_ended``.
  173. ``animation_ended`` is the function that will be called by :ref:`AnimationPlayer <class_AnimationPlayer>` when it's done playing a animation.
  174. For certain animation states, we may need to transition into another state when its finished. To handle this, we
  175. check for every possible animation state. If we need to, we transition into another state.
  176. .. warning:: If you are using your own animated models, make sure that none of the animations are set
  177. to loop. Looping animations do not send the ``animation_finished`` signal when they reach
  178. the end of the animation and are about to loop again.
  179. .. note:: the transitions in ``animation_ended`` ideally would be part of the data in ``states``, but in
  180. an effort to make the tutorial easier to understand, we'll hard code each state transition
  181. in ``animation_ended``.
  182. _________
  183. Finally we have ``animation_callback``. This function will be called by a function track in our animations.
  184. If we have a :ref:`FuncRef <class_FuncRef>` assigned to ``callback_function``, then we call that passed in function. If we do not
  185. have a :ref:`FuncRef <class_FuncRef>` assigned to ``callback_function``, we print out a warning to the console.
  186. .. tip:: Try running ``Testing_Area.tscn`` to make sure there is no runtime issues. If the game runs but nothing
  187. seems to have changed, then everything is working correctly.
  188. Getting the animations ready
  189. ----------------------------
  190. Now that we have a working animation manager, we need to call it from our player script.
  191. Before that though, we need to set some animation callback tracks in our firing animations.
  192. Open up ``Player.tscn`` if you don't have it open and navigate to the :ref:`AnimationPlayer <class_AnimationPlayer>` node
  193. (``Player`` -> ``Rotation_Helper`` -> ``Model`` -> ``Animation_Player``).
  194. We need to attach a function track to three of our animations: The firing animation for the pistol, rifle, and knife.
  195. Let's start with the pistol. Click the animation drop down list and select "Pistol_fire".
  196. Now scroll down to the bottom of the list of animation tracks. The final item in the list should read
  197. ``Armature/Skeleton:Left_UpperPointer``. Now at the bottom of the list, click the plus icon on the bottom
  198. bar of animation window, right next to the loop button and the up arrow.
  199. .. image:: img/AnimationPlayerAddTrack.png
  200. This will bring up a window with three choices. We're wanting to add a function callback track, so click the
  201. option that reads "Add Call Func Track". This will open a window showing the entire node tree. Navigate to the
  202. :ref:`AnimationPlayer <class_AnimationPlayer>` node, select it, and press OK.
  203. .. image:: img/AnimationPlayerCallFuncTrack.png
  204. Now at the bottom of list of animation tracks you will have a green track that reads "AnimationPlayer".
  205. Now we need to add the point where we want to call our callback function. Scrub the timeline until you
  206. reach the point where the muzzle starts to flash.
  207. .. note:: The timeline is the window where all of the points in our animation are stored. Each of the little
  208. points represents a point of animation data.
  209. Scrubbing the timeline means moving ourselves through the animation. So when we say "scrub the timeline
  210. until you reach a point", what we mean is move through the animation window until you reach the a point
  211. on the timeline.
  212. Also, the muzzle of a gun is the end point where the bullet comes out. The muzzle flash is the flash of
  213. light that escapes the muzzle when a bullet is fired. The muzzle is also sometimes referred to as the
  214. barrel of the gun.
  215. .. tip:: For finer control when scrubbing the timeline, press ``control`` and scroll forwards with the mouse wheel to zoom in.
  216. Scrolling backwards will zoom out.
  217. You can also change how the timeline scrubbing snaps by changing the value in ``Step (s)`` to a lower/higher value.
  218. Once you get to a point you like, press the little green plus symbol on the far right side of the
  219. ``AnimationPlayer`` track. This will place a little green point at the position you are currently
  220. at in the animation on your ``AnimationPlayer`` track.
  221. .. image:: img/AnimationPlayerAddPoint.png
  222. Now we have one more step before we are done with the pistol. Select the "enable editing of individual keys"
  223. button on the far right corner of the animation window. It looks like a pencil with a little point beside it.
  224. .. image:: img/AnimationPlayerEditPoints.png
  225. Once you've click that, a new window will open on the right side. Now click the green point on the ``AnimationPlayer``
  226. track. This will bring up the information associated with that point in the timeline. In the empty name field, enter
  227. ``animation_callback`` and press ``enter``.
  228. Now when we are playing this animation the callback function will be triggered at that specific point of the animation.
  229. .. warning:: Be sure to press the "enable editing of individual keys" button again to turn off the ability to edit individual keys
  230. so you cannot change one of the transform tracks by accident!
  231. _________
  232. Let's repeat the process for the rifle and knife firing animations!
  233. .. note:: Because the process is exactly the same as the pistol, the process is going to explained in a little less depth.
  234. Follow the steps in the above if you get lost! It is exactly the same, just on a different animation.
  235. Go to the "Rifle_fire" animation from the animation drop down. Add the function callback track once you reach the bottom of the
  236. animation track list by clicking the little plus icon at the bottom of the screen. Find the point where the muzzle starts
  237. to flash and click the little green plus symbol to add a function callback point at that position on the track.
  238. Next, click the "enable editing of individual keys" button.
  239. Select the newly created function callback point, put "animation_callback" into the name field and press ``enter``.
  240. Click the "enable editing of individual keys" button again to turn off individual key editing.
  241. so we cannot change one of the transform tracks by accident.
  242. Now we need to apply the callback function track to the knife animation. Select the "Knife_fire" animation and scroll to the bottom of the
  243. animation tracks. Click the plus symbol at the bottom of the animation window and add a function callback track.
  244. Next find a point around the first third of the animation to place the animation callback function point at.
  245. .. note:: We will not actually be firing the knife, and the animation is a stabbing animation rather than a firing one.
  246. For this tutorial we are reusing the gun firing logic for our knife, so the animation has been named in a style that
  247. is consistent with the other animations.
  248. From there click the little green plus to add a function callback point at the current position. Then click the "enable editing of individual keys"
  249. button, the button with a plus at the bottom right side of the animation window.
  250. Select the newly created function callback point, put "animation_callback" into the name field and press ``enter``.
  251. Click the "enable editing of individual keys" button again to turn off individual key editing.
  252. so we cannot change one of the transform tracks by accident.
  253. .. tip:: Be sure to save your work!
  254. With that done, we are almost ready to start adding the ability to fire to our player script! We need to setup one last scene:
  255. The scene for our bullet object.
  256. Creating the bullet scene
  257. -------------------------
  258. There are several ways to handle a gun's bullets in video games. In this tutorial series,
  259. we will be exploring two of the more common ways: Objects, and raycasts.
  260. _________
  261. One of the two ways is using a bullet object. This will be an object that travels through the world and handles
  262. its own collision code. This method we create/spawn a bullet object in the direction our gun is facing, and then
  263. it sends itself forward.
  264. There are several advantages to this method. The first being we do not have to store the bullets in our player. We can simply create the bullet
  265. and then move on, and the bullet itself with handle checking for collisions, sending the proper signal(s) to the object it collides with, and destroying itself.
  266. Another advantage is we can have more complex bullet movement. If we want to make the bullet fall ever so slightly as time goes on, we can make the bullet
  267. controlling script slowly push the bullet towards the ground. Using a object also makes the bullet take time to reach its target, it doesn't instantly
  268. hit whatever its pointed at. This feels more realistic because nothing in real life moves instantly from one point to another.
  269. One of the huge disadvantages performance. While having each bullet calculate their own paths and handle their own collision allows for a lot of flexibility,
  270. it comes at the cost of performance. With this method we are calculating every bullet's movement every step, and while this may not be a problem for a few dozen
  271. bullets, it can become a huge problem when you potentially have several hundred bullets.
  272. Despite the performance hit, many first person shooters include some form of object bullets. Rocket launchers are a prime example because in many
  273. first person shooters, rockets do not just instantly explode at their target position. You can also find bullets as object many times with grenades
  274. because they generally bounce around the world before exploding.
  275. .. note:: While I cannot say for sure this is the case, these games *probably* use bullet objects in some form or another:
  276. (These are entirely from my observations. **They may be entirely wrong**. I have never worked on **any** of the following games)
  277. - Halo (Rocket launchers, fragment grenades, sniper rifles, brute shot, and more)
  278. - Destiny (Rocket launchers, grenades, fusion rifles, sniper rifles, super moves, and more)
  279. - Call of Duty (Rocket launchers, grenades, ballistic knives, crossbows, and more)
  280. - Battlefield (Rocket launchers, grenades, claymores, mortars, and more)
  281. Another disadvantage with bullet objects is networking. Bullet objects have to sync the positions (at least) with however many clients are connected
  282. to the server.
  283. While we are not implementing any form of networking (as that would be it's own entire tutorial series), it is a consideration
  284. to keep in mind when creating your first person shooter, especially if you plan on adding some form of networking in the future.
  285. _________
  286. The other way of handling bullet collisions we will be looking at, is raycasting.
  287. This method is extremely common in guns that have fast moving bullets that rarely change trajectory change over time.
  288. Instead of creating a bullet object and sending it through space, we instead send a ray starting from the barrel/muzzle of the gun forwards.
  289. We set the raycast's origin to the starting position of the bullet, and based on the length we can adjust how far the bullet 'travels' through space.
  290. .. note:: While I cannot say for sure this is the case, these games *probably* use raycasts in some form or another:
  291. (These are entirely from my observations. **They may be entirely wrong**. I have never worked on **any** of the following games)
  292. - Halo (Assault rifles, DMRs, battle rifles, covenant carbine, spartan laser, and more)
  293. - Destiny (Auto rifles, pulse rifles, scout rifles, hand cannons, machine guns, and more)
  294. - Call of Duty (Assault rifles, light machine guns, sub machine guns, pistols, and more)
  295. - Battlefield (Assault rifles, SMGs, carbines, pistols, and more)
  296. One huge advantage for this method is it's light on performance.
  297. Sending a couple hundred rays through space is *way* easier for the computer to calculate than sending a couple hundred
  298. bullet objects.
  299. Another advantage is we can instantly know if we've hit something or not exactly when we call for it. For networking this is important because we do not need
  300. to sync the bullet movements over the Internet, we only need to send whether or not the raycast hit.
  301. Raycasting does have some disadvantages though. One major disadvantage is we cannot easily cast a ray in anything but a linear line.
  302. This means we can only fire in a straight line for however long our ray length is. You can create the illusion of bullet movement by casting
  303. multiple rays at different positions, but not only is this hard to implement in code, it is also is heavier on performance.
  304. Another disadvantage is we cannot see the bullet. With bullet objects we can actually see the bullet travel through space if we attach a mesh
  305. to it, but because raycasts happen instantly, we do not have a decent way of showing the bullets. You could draw a line from the origin of the
  306. raycast to the point where the raycast collided, and that is one popular way of showing raycasts. Another way is simply not drawing the raycast
  307. at all, because theoretically the bullets move so fast our eyes could not see it anyway.
  308. _________
  309. Lets get the bullet object setup. This is what our pistol will create when the "Pistol_fire" animation callback function is called.
  310. Open up ``Bullet_Scene.tscn``. The scene contains :ref:`Spatial <class_Spatial>` node called bullet, with a :ref:`MeshInstance <class_MeshInstance>`
  311. and an :ref:`Area <class_Area>` with a :ref:`CollisionShape <class_CollisionShape>` childed to it.
  312. Create a new script called ``Bullet_script.gd`` and attach it to the ``Bullet`` :ref:`Spatial <class_Spatial>`.
  313. We are going to move the entire bullet object at the root (``Bullet``). We will be using the :ref:`Area <class_Area>` to check whether or not we've collided with something
  314. .. note:: Why are we using a :ref:`Area <class_Area>` and not a :ref:`RigidBody <class_RigidBody>`? The mean reason we're not using a :ref:`RigidBody <class_RigidBody>`
  315. is because we do not want the bullet to interact with other :ref:`RigidBody <class_RigidBody>` nodes.
  316. By using an :ref:`Area <class_Area>` we are assuring that none of the other :ref:`RigidBody <class_RigidBody>` nodes, including other bullets, will be effected.
  317. Another reason is simply because it is easier to detect collisions with a :ref:`Area <class_Area>`!
  318. Here's the script that will control our bullet:
  319. ::
  320. extends Spatial
  321. var BULLET_SPEED = 70
  322. var BULLET_DAMAGE = 15
  323. const KILL_TIMER = 4
  324. var timer = 0
  325. var hit_something = false
  326. func _ready():
  327. $Area.connect("body_entered", self, "collided")
  328. func _physics_process(delta):
  329. var forward_dir = global_transform.basis.z.normalized()
  330. global_translate(forward_dir * BULLET_SPEED * delta)
  331. timer += delta
  332. if timer >= KILL_TIMER:
  333. queue_free()
  334. func collided(body):
  335. if hit_something == false:
  336. if body.has_method("bullet_hit"):
  337. body.bullet_hit(BULLET_DAMAGE, self.global_transform.origin)
  338. hit_something = true
  339. queue_free()
  340. Lets go through the script:
  341. _________
  342. First we define a few global variables:
  343. - ``BULLET_SPEED``: The speed the bullet travels at.
  344. - ``BULLET_DAMAGE``: The damage the bullet will cause to whatever it collides with.
  345. - ``KILL_TIMER``: How long the bullet can last without hitting anything.
  346. - ``timer``: A float for tracking how long we've been alive.
  347. - ``hit_something``: A boolean for tracking whether or not we've hit something.
  348. With the exception of ``timer`` and ``hit_something``, all of these variables
  349. change how the bullet interacts with the world.
  350. .. note:: The reason we are using a kill timer is so we do not have a case where we
  351. get a bullet travelling forever. By using a kill timer, we can assure that
  352. no bullets will travel forever and consume resources.
  353. .. tip:: As in :ref:`doc_fps_tutorial_part_one`, we have a couple all uppercase global variables. The reason behind this is the same
  354. as the reason given in :ref:`doc_fps_tutorial_part_one`: We want to treat these variables like constants, but we want to be
  355. able to change them. In this case we will later need to change the damage and speed of these bullets,
  356. so we need them to be variables and not constants.
  357. _________
  358. In ``_ready`` we set the area's ``body_entered`` signal to ourself so that it calls
  359. the ``collided`` function when a body enters the area.
  360. _________
  361. ``_physics_process`` gets the bullet's local ``Z`` axis. If you look in at the scene
  362. in local mode, you will find that the bullet faces the positive local ``Z`` axis.
  363. Next we translate the entire bullet by that forward direction, multiplying in our speed and delta time.
  364. After that we add delta time to our timer and check if the timer has as long or longer
  365. than our ``KILL_TIME`` constant. If it has, we use ``queue_free`` to free ourselves.
  366. _________
  367. In ``collided`` we check if we've hit something yet or not.
  368. Remember that ``collided`` is only called when a body has entered the :ref:`Area <class_Area>` node.
  369. If we have not already collided with something, we then proceed to check if the body we've collided
  370. with has a function/method called ``bullet_hit``. If it does, we call it and pass in our damage and our position.
  371. .. note:: in ``collided``, the passed in body can be a :ref:`StaticBody <class_StaticBody>`,
  372. :ref:`RigidBody <class_RigidBody>`, or :ref:`KinematicBody <class_KinematicBody>`
  373. We set ``hit_something`` to ``true`` because regardless of whether or not the body
  374. the bullet collided with has the ``bullet_hit`` function/method, it has hit something and so we need to not hit anything else.
  375. Then we free the bullet using ``queue_free``.
  376. .. tip:: You may be wondering why we even have a ``hit_something`` variable if we
  377. free the bullet using ``queue_free`` as soon as it hits something.
  378. The reason we need to track whether we've hit something or not is because ``queue_free``
  379. does not immediately free the node, so the bullet could collide with another body
  380. before Godot has a chance to free it. By tracking if the bullet has hit something
  381. we can make sure that the bullet will only hit one object.
  382. _________
  383. Before we start programming the player again, let's take a quick look at ``Player.tscn``.
  384. Open up ``Player.tscn`` again.
  385. Expand ``Rotation_Helper`` and notice how it has two nodes: ``Gun_Fire_Points`` and
  386. ``Gun_Aim_Point``.
  387. ``Gun_aim_point`` is the point that the bullets will be aiming at. Notice how it
  388. is lined up with the center of the screen and pulled a distance forward on the Z
  389. axis. ``Gun_aim_point`` will serve as the point the bullets will for sure collide
  390. with as it goes along.
  391. .. note:: There is a invisible mesh instance for debugging purposes. The mesh is
  392. a small sphere that visually shows where the bullets will be aiming.
  393. Open up ``Gun_Fire_Points`` and you'll find three more :ref:`Spatial <class_Spatial>` nodes, one for each
  394. weapon.
  395. Open up ``Rifle_Point`` and you'll find a :ref:`Raycast <class_Raycast>` node. This is where
  396. we will be sending the raycasts for our rifle's bullets.
  397. The length of the raycast will dictate how far our bullets will travel.
  398. We are using a :ref:`Raycast <class_Raycast>` node to handle the rifle's bullet because
  399. we want to fire lots of bullets quickly. If we use bullet objects, it is quite possible
  400. we could run into performance issues on older machines.
  401. .. note:: If you are wondering where the positions of the points came from, they
  402. are the rough positions of the ends of each weapon. You can see this by
  403. going to ``AnimationPlayer``, selecting one of the firing animations
  404. and scrubbing through the timeline. The point for each weapon should mostly line
  405. up with the end of each weapon.
  406. Open up ``Knife_Point`` and you'll find a :ref:`Area <class_Area>` node. We are using a :ref:`Area <class_Area>` for the knife
  407. because we only care for all of the bodies close to us, and because our knife does
  408. not fire into space. If we were making a throwing knife, we would likely spawn a bullet
  409. object that looks like a knife.
  410. Finally, we have ``Pistol_Point``. This is the point where we will be creating/instancing
  411. our bullet objects. We do not need any additional nodes here, as the bullet handles all
  412. of its own collision detection.
  413. Now that we've seen how we will handle our other weapons, and where we will spawn the bullets,
  414. let's start working on making them work.
  415. .. note:: You can also look at the HUD nodes if you want. There is nothing fancy there and other
  416. than using a single :ref:`Label <class_Label>`, we will not be touching any of those nodes.
  417. Check :ref:`doc_design_interfaces_with_the_control_nodes` for a tutorial on using GUI nodes.
  418. Creating the first weapon
  419. -------------------------
  420. Lets write the code for each of our weapons, starting with the pistol.
  421. Select ``Pistol_Point`` (``Player`` -> ``Rotation_Helper`` -> ``Gun_Fire_Points`` -> ``Pistol_Point``) and create a new script called ``Weapon_Pistol.gd``.
  422. Add the following code to ``Weapon_Pistol.gd``:
  423. ::
  424. extends Spatial
  425. const DAMAGE = 15
  426. const IDLE_ANIM_NAME = "Pistol_idle"
  427. const FIRE_ANIM_NAME = "Pistol_fire"
  428. var is_weapon_enabled = false
  429. var bullet_scene = preload("Bullet_Scene.tscn")
  430. var player_node = null
  431. func _ready():
  432. pass
  433. func fire_weapon():
  434. var clone = bullet_scene.instance()
  435. var scene_root = get_tree().root.get_children()[0]
  436. scene_root.add_child(clone)
  437. clone.global_transform = self.global_transform
  438. clone.scale = Vector3(4, 4, 4)
  439. clone.BULLET_DAMAGE = DAMAGE
  440. func equip_weapon():
  441. if player_node.animation_manager.current_state == IDLE_ANIM_NAME:
  442. is_weapon_enabled = true
  443. return true
  444. if player_node.animation_manager.current_state == "Idle_unarmed":
  445. player_node.animation_manager.set_animation("Pistol_equip")
  446. return false
  447. func unequip_weapon():
  448. if player_node.animation_manager.current_state == IDLE_ANIM_NAME:
  449. if player_node.animation_manager.current_state != "Pistol_unequip":
  450. player_node.animation_manager.set_animation("Pistol_unequip")
  451. if player_node.animation_manager.current_state == "Idle_unarmed":
  452. is_weapon_enabled = false
  453. return true
  454. else:
  455. return false
  456. Let's go over how the script works.
  457. _________
  458. First we define some global variables we'll need in the script:
  459. * ``DAMAGE``: The amount of damage a single bullet does.
  460. * ``IDLE_ANIM_NAME``: The name of the pistol's idle animation.
  461. * ``FIRE_ANIM_NAME``: The name of the pistol's fire animation.
  462. * ``is_weapon_enabled``: A variable for checking whether this weapon is in use/enabled.
  463. * ``bullet_scene``: The bullet scene we worked on earlier.
  464. * ``player_node``: A variable to hold ``Player.gd``.
  465. The reason we define most of these variables is so we can use them in ``Player.gd``.
  466. All of the weapons we'll make will have all of these variables (minus ``bullet_scene``) so we have
  467. a consistent interface to interact with in ``Player.gd``. By using the same variables/functions in each
  468. weapon, we can interact with them without having to know which weapon we are using, which makes our code
  469. much more modular because we can add weapons without having to change much of the code in ``Player.gd`` and it will just work.
  470. If we could write all of the code in ``Player.gd``, but then ``Player.gd`` will get increasingly harder to manage as we add weapons.
  471. By using a modular design with a consistent interface, we can keep ``Player.gd`` nice and neat, while also making it easier to add/remove/modify weapons.
  472. _________
  473. In ``_ready`` we simply pass over it.
  474. There is one thing of note though, an assumption we're assuming we'll fill in ``Player.gd``.
  475. We are going to assume that ``Player.gd`` will pass themselves in before calling any of the functions in ``Weapon_Pistol.gd``.
  476. While this can lead to situations where the player does not pass themselves in (because we forget), we would have to have a long string
  477. of ``get_parent`` calls to traverse up the scene tree to retrieve the player. This does not look pretty (``get_parent().get_parent().get_parent()`` and so on)
  478. and it is relatively safe to assume we will remember to pass ourselves to each weapon in ``Player.gd``.
  479. _________
  480. Next let's look at ``fire_weapon``:
  481. The first thing we do is instance the bullet scene we made earlier.
  482. .. tip:: By instancing the scene, we are creating a new node holding all of the node(s) in the scene we instanced, effectively cloning that scene.
  483. Then we add ``clone`` to the first child node of the root of the scene we are currently in. By doing this we're making it at a child of the root node of the currently loaded scene.
  484. In other words, we are adding ``clone`` as a child of the first node (whatever is at the top of the scene tree) in the currently loaded/opened scene.
  485. If the currently loaded/open scene is ``Testing_Area.tscn``, we'd be adding our ``clone`` as a child of ``Testing_Area``, the root node in that scene.
  486. .. warning:: As mentioned later below in the section on adding sounds, this method makes a assumption. This will be explained later
  487. in the section on adding sounds in :ref:`doc_fps_tutorial_part_three`
  488. Next we set the global transform of the clone to the ``Pistol_Aim_Point``'s global transform. The reason we do this is so the bullet is spawned at the end of the pistol.
  489. You can see that ``Pistol_Aim_Point`` is positioned right at the end of the pistol by clicking the :ref:`AnimationPlayer <class_AnimationPlayer>` and
  490. scrolling through ``Pistol_fire``. You'll find the position more or less is at the end of the pistol when it fires.
  491. Next we scale it up by a factor of ``4`` because the bullet scene is a little too small by default.
  492. Then we set the bullet's damage (``BULLET_DAMAGE``) to the amount of damage a single pistol bullet does (``DAMAGE``)
  493. _________
  494. Now let's look at ``equip_weapon``:
  495. The first thing we do is check to see if the animation manager is in the pistol's idle animation.
  496. If we are in the pistol's idle animation, we set ``is_weapon_enabled`` to ``true`` and return ``true`` because we have successfully
  497. been equipped.
  498. Because we know our pistol's ``equip`` animation automatically transitions to the pistol's idle animation, if we are in the pistol's
  499. idle animation we most have finished playing the equip animation.
  500. .. note:: We know these animations will transition because we wrote to the code to make them transition in ``Animation_Manager.gd``
  501. Next we check to see if we are in the ``Idle_unarmed`` animation state. Because all unequipping animations go to this state, and because any
  502. weapon can be equipped from this state, we change animations to ``Pistol_equip`` if we are in ``Idle_unarmed``.
  503. Since we know ``Pistol_equip`` will transition to ``Pistol_idle``, we do not need to do any more additional processing for equipping weapons,
  504. but since we were not able to equip the pistol yet, we return ``false``.
  505. _________
  506. Finally, let's look at ``unequip_weapon``:
  507. ``unequip_weapon`` is similar to ``equip_weapon``, but instead we're checking things in reverse.
  508. First we check to see if we are in our idle animation. Then check to make sure we are not in the ``Pistol_unequip`` animation.
  509. If we are not in the ``Pistol_unequip`` animation, we want to play ``pistol_unequip``.
  510. .. note:: You may be wondering why we are checking to see if we are the pistol's idle animation, and then making sure we are not unequipping right after.
  511. The reason behind the additional check is because we could (in rare cases) call ``unequip_weapon`` twice before we've had a chance to process ``set_animation``,
  512. so we add this additional check to make sure the unequip animation plays.
  513. Next we check to see if we are in ``Idle_unarmed``, which is the animation state we will transition into from ``Pistol_unequip``. If we are, then we set
  514. ``is_weapon_enabled`` to false since we are no longer using this weapon, and return ``true`` because we have successfully unequipped the pistol.
  515. If we are not in ``Idle_unarmed``, we return ``false`` because we have not yet successfully unequipped the pistol.
  516. Creating the other two weapons
  517. ------------------------------
  518. Now that we all of the code we'll need for the pistol, let's add the code for the rifle and knife next.
  519. Select ``Rifle_Point`` (``Player`` -> ``Rotation_Helper`` -> ``Gun_Fire_Points`` -> ``Rifle_Point``) and create a new script called ``Weapon_Rifle.gd``,
  520. then add the following:
  521. ::
  522. extends Spatial
  523. const DAMAGE = 4
  524. const IDLE_ANIM_NAME = "Rifle_idle"
  525. const FIRE_ANIM_NAME = "Rifle_fire"
  526. var is_weapon_enabled = false
  527. var player_node = null
  528. func _ready():
  529. pass
  530. func fire_weapon():
  531. var ray = $Ray_Cast
  532. ray.force_raycast_update()
  533. if ray.is_colliding():
  534. var body = ray.get_collider()
  535. if body == player_node:
  536. pass
  537. elif body.has_method("bullet_hit"):
  538. body.bullet_hit(DAMAGE, ray.get_collision_point())
  539. func equip_weapon():
  540. if player_node.animation_manager.current_state == IDLE_ANIM_NAME:
  541. is_weapon_enabled = true
  542. return true
  543. if player_node.animation_manager.current_state == "Idle_unarmed":
  544. player_node.animation_manager.set_animation("Rifle_equip")
  545. return false
  546. func unequip_weapon():
  547. if player_node.animation_manager.current_state == IDLE_ANIM_NAME:
  548. if player_node.animation_manager.current_state != "Rifle_unequip":
  549. player_node.animation_manager.set_animation("Rifle_unequip")
  550. if player_node.animation_manager.current_state == "Idle_unarmed":
  551. is_weapon_enabled = false
  552. return true
  553. return false
  554. Most of this is exactly the same as ``Weapon_Pistol.gd``, so we're only going to look at what's changed: ``fire_weapon``.
  555. The first thing we do is get the :ref:`Raycast <class_Raycast>` node, which is a child of ``Rifle_Point``.
  556. Next we force the raycast to update using ``force_raycast_update``. This will force the raycast to detect collisions when we call it, meaning
  557. we get a frame perfect collision check with the 3D physics world.
  558. Then we check to see if the raycast collided with something.
  559. If the raycast has collided with something, we first get the collision body it collided with. This can be a :ref:`StaticBody <class_StaticBody>`,
  560. :ref:`RigidBody <class_RigidBody>`, or a :ref:`KinematicBody <class_KinematicBody>`.
  561. Next we want to make sure the body we've collided with is not the player, since we (probably) do not want to give the player the ability to shoot themselves in the foot.
  562. If the body is not the player, we then check to see if they have a function/method called ``bullet_hit``. If they do, we call it and pass in the amount of
  563. damage this bullet does (``DAMAGE``), and the point where the raycast collided with the body.
  564. _________
  565. Now all we need to do is write the code for the knife.
  566. Select ``Knife_Point`` (``Player`` -> ``Rotation_Helper`` -> ``Gun_Fire_Points`` -> ``Knife_Point``) and create a new script called ``Weapon_Knife.gd``,
  567. then add the following:
  568. ::
  569. extends Spatial
  570. const DAMAGE = 40
  571. const IDLE_ANIM_NAME = "Knife_idle"
  572. const FIRE_ANIM_NAME = "Knife_fire"
  573. var is_weapon_enabled = false
  574. var player_node = null
  575. func _ready():
  576. pass
  577. func fire_weapon():
  578. var area = $Area
  579. var bodies = area.get_overlapping_bodies()
  580. for body in bodies:
  581. if body == player_node:
  582. continue
  583. if body.has_method("bullet_hit"):
  584. body.bullet_hit(DAMAGE, area.global_transform.origin)
  585. func equip_weapon():
  586. if player_node.animation_manager.current_state == IDLE_ANIM_NAME:
  587. is_weapon_enabled = true
  588. return true
  589. if player_node.animation_manager.current_state == "Idle_unarmed":
  590. player_node.animation_manager.set_animation("Knife_equip")
  591. return false
  592. func unequip_weapon():
  593. if player_node.animation_manager.current_state == IDLE_ANIM_NAME:
  594. player_node.animation_manager.set_animation("Knife_unequip")
  595. if player_node.animation_manager.current_state == "Idle_unarmed":
  596. is_weapon_enabled = false
  597. return true
  598. return false
  599. As with ``Weapon_Rifle.gd``, the only differences are in ``fire_weapon``, so let's look at that:
  600. The first thing we do is get the :ref:`Area <class_Area>` child node of ``Knife_Point``.
  601. Next we want to get all of the collision bodies inside the area using ``get_overlapping_bodies``. This will return a
  602. list of every body that touches the area.
  603. We next want to go through each of those bodies.
  604. First we check to make sure the body is not the player, because we do not want to be able to stab ourselves. If the body is the player,
  605. we use ``continue`` so we jump to looking at the next body in ``bodies``.
  606. If we have not jumped to the next body, we then check to see if the body has the ``bullet_hit`` function/method. If it does,
  607. we call it, passing in the amount of damage a single knife swipe does (``DAMAGE``) and the position of the :ref:`Area <class_Area>`.
  608. .. note:: While we could attempt to calculate a rough location for where the knife hit, we
  609. do not bother because using the area's position works well enough and the extra time
  610. needed to calculate a rough position for each body is not worth the effort.
  611. Making the weapons work
  612. -----------------------
  613. Lets start making the weapons work in ``Player.gd``.
  614. First lets start by adding some global variables we'll need for the weapons:
  615. ::
  616. # Place before _ready
  617. var animation_manager
  618. var current_weapon_name = "UNARMED"
  619. var weapons = {"UNARMED":null, "KNIFE":null, "PISTOL":null, "RIFLE":null}
  620. const WEAPON_NUMBER_TO_NAME = {0:"UNARMED", 1:"KNIFE", 2:"PISTOL", 3:"RIFLE"}
  621. const WEAPON_NAME_TO_NUMBER = {"UNARMED":0, "KNIFE":1, "PISTOL":2, "RIFLE":3}
  622. var changing_weapon = false
  623. var changing_weapon_name = "UNARMED"
  624. var health = 100
  625. var UI_status_label
  626. Lets go over what these new variables will do:
  627. - ``animation_manager``: This will hold the :ref:`AnimationPlayer <class_AnimationPlayer>` node and its script, which we wrote previously.
  628. - ``current_weapon_name``: The name of the weapon we are currently using. It has four possible values: ``UNARMED``, ``KNIFE``, ``PISTOL``, and ``RIFLE``.
  629. - ``weapons``: A dictionary that will hold all of the weapon nodes.
  630. - ``WEAPON_NUMBER_TO_NAME``: A dictionary allowing us to convert from a weapon's number to its name. We'll use this for changing weapons.
  631. - ``WEAPON_NAME_TO_NUMBER``: A dictionary allowing us to convert from a weapon's name to its number. We'll use this for changing weapons.
  632. - ``changing_weapon``: A boolean to track whether or not we are changing guns/weapons.
  633. - ``changing_weapon_name``: The name of the weapon we want to change to.
  634. - ``health``: How much health our player has. In this part of the tutorial we will not be using it.
  635. - ``UI_status_label``: A label to show how much health we have, and how much ammo we have both in our gun and in reserves.
  636. _________
  637. Next we need to add a few things in ``_ready``. Here's the new ``_ready`` function:
  638. ::
  639. func _ready():
  640. camera = $Rotation_Helper/Camera
  641. rotation_helper = $Rotation_Helper
  642. animation_manager = $Rotation_Helper/Model/Animation_Player
  643. animation_manager.callback_function = funcref(self, "fire_bullet")
  644. Input.set_mouse_mode(Input.MOUSE_MODE_CAPTURED)
  645. weapons["KNIFE"] = $Rotation_Helper/Gun_Fire_Points/Knife_Point
  646. weapons["PISTOL"] = $Rotation_Helper/Gun_Fire_Points/Pistol_Point
  647. weapons["RIFLE"] = $Rotation_Helper/Gun_Fire_Points/Rifle_Point
  648. var gun_aim_point_pos = $Rotation_Helper/Gun_Aim_Point.global_transform.origin
  649. for weapon in weapons:
  650. var weapon_node = weapons[weapon]
  651. if weapon_node != null:
  652. weapon_node.player_node = self
  653. weapon_node.look_at(gun_aim_point_pos, Vector3(0, 1, 0))
  654. weapon_node.rotate_object_local(Vector3(0, 1, 0), deg2rad(180))
  655. current_weapon_name = "UNARMED"
  656. changing_weapon_name = "UNARMED"
  657. UI_status_label = $HUD/Panel/Gun_label
  658. flashlight = $Rotation_Helper/Flashlight
  659. Let's go over what's changed.
  660. First we get the :ref:`AnimationPlayer <class_AnimationPlayer>` node and assign it to our animation_manager variable. Then we set the callback function
  661. to a :ref:`FuncRef <class_FuncRef>` that will call the player's ``fire_bullet`` function. Right now we haven't written our fire_bullet function,
  662. but we'll get there soon.
  663. Next we get all of the weapon nodes and assign them to ``weapons``. This will allow us to access the weapon nodes only with their name
  664. (``KNIFE``, ``PISTOL``, or ``RIFLE``).
  665. We then get ``Gun_Aim_Point``'s global position so we can rotate our weapons to aim at it.
  666. Then we go through each weapon in ``weapons``.
  667. We first get the weapon node. If the weapon node is not ``null``, we then set it's ``player_node`` variable to ourself.
  668. Then we have it look at ``gun_aim_point_pos``, and then rotate it by ``180`` degrees on the ``Y`` axis.
  669. .. note:: We rotate all of those weapon points by ``180`` degrees on their ``Y`` axis because our camera is pointing backwards.
  670. If we did not rotate all of these weapon points by ``180`` degrees, all of the weapons would fire backwards.
  671. Then we set ``current_weapon_name`` and ``changing_weapon_name`` to ``UNARMED``.
  672. Finally, we get the UI :ref:`Label <class_Label>` from our HUD.
  673. _________
  674. Lets add a new function call to ``_physics_process`` so we can change weapons. Here's the new code:
  675. ::
  676. func _physics_process(delta):
  677. process_input(delta)
  678. process_movement(delta)
  679. process_changing_weapons(delta)
  680. Now we will call ``process_changing_weapons``.
  681. _________
  682. Now lets add all of the player input code for the weapons in ``process_input``. Add the following code:
  683. ::
  684. # ----------------------------------
  685. # Changing weapons.
  686. var weapon_change_number = WEAPON_NAME_TO_NUMBER[current_weapon_name]
  687. if Input.is_key_pressed(KEY_1):
  688. weapon_change_number = 0
  689. if Input.is_key_pressed(KEY_2):
  690. weapon_change_number = 1
  691. if Input.is_key_pressed(KEY_3):
  692. weapon_change_number = 2
  693. if Input.is_key_pressed(KEY_4):
  694. weapon_change_number = 3
  695. if Input.is_action_just_pressed("shift_weapon_positive"):
  696. weapon_change_number += 1
  697. if Input.is_action_just_pressed("shift_weapon_negative"):
  698. weapon_change_number -= 1
  699. weapon_change_number = clamp(weapon_change_number, 0, WEAPON_NUMBER_TO_NAME.size()-1)
  700. if changing_weapon == false:
  701. if WEAPON_NUMBER_TO_NAME[weapon_change_number] != current_weapon_name:
  702. changing_weapon_name = WEAPON_NUMBER_TO_NAME[weapon_change_number]
  703. changing_weapon = true
  704. # ----------------------------------
  705. # ----------------------------------
  706. # Firing the weapons
  707. if Input.is_action_pressed("fire"):
  708. if changing_weapon == false:
  709. var current_weapon = weapons[current_weapon_name]
  710. if current_weapon != null:
  711. if animation_manager.current_state == current_weapon.IDLE_ANIM_NAME:
  712. animation_manager.set_animation(current_weapon.FIRE_ANIM_NAME)
  713. # ----------------------------------
  714. Lets go over the additions, starting with how we're changing weapons.
  715. First we get the current weapon's number and assign it to ``weapon_change_number``.
  716. Then we check to see if any of the number keys (keys 1-4) are pressed. If they are, we set
  717. ``weapon_change_number`` to the value mapped at that key.
  718. .. note:: The reason key 1 is mapped to ``0`` is because the first element in a list is mapped to zero, not one. Most list/array accessors
  719. in most programming languages start at ``0`` instead of ``1``. See https://en.wikipedia.org/wiki/Zero-based_numbering for more information.
  720. Next we check to see if ``shift_weapon_positive`` or ``shift_weapon_negative`` is pressed. If one of them are, we add/subtract ``1`` from
  721. ``weapon_change_number``.
  722. Because we may have shifted ``weapon_change_number`` outside of the number of weapons we have, we clamp it so it cannot exceed the maximum number of weapons we have
  723. and has to be ``0`` or more.
  724. Then we check to make sure we are not already changing weapons. If we are not, we then check to see if the weapon we want to change to
  725. is a new weapon and not the one we are currently using. If the weapon we're wanting to change to is a new weapon, we then set ``changing_weapon_name`` to
  726. the weapon at ``weapon_change_number`` and set ``changing_weapon`` to true.
  727. For firing the weapon we first check to see if the ``fire`` action is pressed.
  728. Then we check to make sure we are not changing weapons.
  729. Next we get the weapon node for the current weapon.
  730. If the current weapon node does not equal null, and we are in it's ``IDLE_ANIM_NAME`` state, we set our animation
  731. to the current weapon's ``FIRE_ANIM_NAME``.
  732. _________
  733. Lets add ``process_changing_weapons`` next.
  734. Add the following code:
  735. ::
  736. func process_changing_weapons(delta):
  737. if changing_weapon == true:
  738. var weapon_unequipped = false
  739. var current_weapon = weapons[current_weapon_name]
  740. if current_weapon == null:
  741. weapon_unequipped = true
  742. else:
  743. if current_weapon.is_weapon_enabled == true:
  744. weapon_unequipped = current_weapon.unequip_weapon()
  745. else:
  746. weapon_unequipped = true
  747. if weapon_unequipped == true:
  748. var weapon_equiped = false
  749. var weapon_to_equip = weapons[changing_weapon_name]
  750. if weapon_to_equip == null:
  751. weapon_equiped = true
  752. else:
  753. if weapon_to_equip.is_weapon_enabled == false:
  754. weapon_equiped = weapon_to_equip.equip_weapon()
  755. else:
  756. weapon_equiped = true
  757. if weapon_equiped == true:
  758. changing_weapon = false
  759. current_weapon_name = changing_weapon_name
  760. changing_weapon_name = ""
  761. Lets go over what's happening here:
  762. The first thing we do is make sure we've recived input to change weapons. We do this by making sure ``changing_weapons`` is ``true``.
  763. Next we define a variable (``weapon_unequipped``) so we can check whether the current weapon has been successfully unequipped or not.
  764. Then we get the current weapon from ``weapons``.
  765. If the current weapon is not ``null``, then we have need to check to see if the weapon is enabled or not. If the weapon is enabled, we call it's ``unequip_weapon`` function
  766. so it will start the unequip animation. If the weapon is not enabled, we set ``weapon_unequippped`` to ``true``, because we the weapon has successfully been unequipped.
  767. If the current weapon is ``null``, then we can simply set ``weapon_unequipped`` to ``true``. The reason we do this check is because there is no weapon script/node for
  768. ``UNARMED``, but there is also no animations for ``UNARMED``, so we can just start equipping the weapon we want to change to.
  769. If we have successfully unequipped the current weapon (``weapon_unequipped == true``), we need to equip the new weapon.
  770. First we define a new variable (``weapon_equipped``) for tracking whether we have successfully equipped the new weapon or not.
  771. Then we get the weapon we want to change to. If the weapon we want to change to is not ``null``, we then check to see whether or not it's enabled. If it is not enabled,
  772. we call it's ``equip_weapon`` function so it starts to equip the weapon. If the weapon is enabled, we set ``weapon_equipped`` to ``true``.
  773. If the weapon we want to change to is ``null``, we simply set ``weapon_equipped`` to ``true`` because we do not have any node/script for ``UNARMED``, nor do we have any animations.
  774. Finally, we check to see if we have successfully equipped the new weapon. If we have, we set ``changing_weapon`` to false because we are no longer changing weapons.
  775. We also set ``current_weapon_name`` to ``changing_weapon_name``, since the current weapon has changed, and then we set ``changing_weapon_name`` to a empty string.
  776. _________
  777. Now, we need to add one more function to the player, and then the player is ready to start the weapons!
  778. We need to add ``fire_bullet``, which will be called when by the :ref:`AnimationPlayer <class_AnimationPlayer>` at those
  779. points we set earlier in the :ref:`AnimationPlayer <class_AnimationPlayer>` function track:
  780. ::
  781. func fire_bullet():
  782. if changing_weapon == true:
  783. return
  784. weapons[current_weapon_name].fire_weapon()
  785. Lets go over what this function is doing:
  786. First we check if we are changing weapons or not. If we are changing weapons, we do not want shoot so we ``return``.
  787. .. tip:: Calling ``return`` stops the rest of the function from being called. In this case, we are not returning a variable
  788. because we are only interested in not running the rest of the code, and because we are not looking for a returned
  789. variable either when we call this function.
  790. Then we tell the current weapon we are using to fire by calling its ``fire_weapon`` function.
  791. .. tip:: Remember how we mentioned the speed of the animations for firing was faster than
  792. the other animations? By changing the firing animation speeds, you can change how
  793. fast the weapon fires bullets!
  794. _______
  795. Before we are ready to test our new weapons, we still have a little bit of work to do.
  796. Creating some test subjects
  797. ---------------------------
  798. Create a new script by going to the scripting window, clicking "file", and selecting new.
  799. Name this script ``RigidBody_hit_test`` and make sure it extends :ref:`RigidBody <class_RigidBody>`.
  800. Now we need to add this code:
  801. ::
  802. extends RigidBody
  803. func _ready():
  804. pass
  805. func bullet_hit(damage, bullet_hit_pos):
  806. var direction_vect = global_transform.origin - bullet_hit_pos
  807. direction_vect = direction_vect.normalized()
  808. apply_impulse(bullet_hit_pos, direction_vect * damage)
  809. Lets go over how ``bullet_hit`` works:
  810. First we get the direction from the bullet pointing towards our global :ref:`Transform <class_Transform>`.
  811. We do this by subtracting the bullet's hit position from the :ref:`RigidBody <class_RigidBody>`'s position.
  812. This results in a :ref:`Vector3 <class_Vector3>` that we can use to tell the direction the bullet collided into the
  813. :ref:`RigidBody <class_RigidBody>` at.
  814. We then normalize it so we do not get crazy results from collisions on the extremes
  815. of the collision shape attached to the :ref:`RigidBody <class_RigidBody>`. Without normalizing shots farther
  816. away from the center of the :ref:`RigidBody <class_RigidBody>` would cause a more noticeable reaction than
  817. those closer to the center.
  818. Finally, we apply an impulse at the passed in bullet collision position. With the force
  819. being the directional vector times the damage the bullet is supposed to cause. This makes
  820. the :ref:`RigidBody <class_RigidBody>` seem to move in response to the bullet colliding into it.
  821. _______
  822. Now we need to attach this script to all of the :ref:`RigidBody <class_RigidBody>` nodes we want to effect.
  823. Open up ``Testing_Area.tscn`` and select all of the cubes parented to the ``Cubes`` node.
  824. .. tip:: If you select the top cube, and then hold down ``shift`` and select the last cube, Godot will
  825. select all of the cubes in between!
  826. Once you have all of the cubes selected, scroll down in the inspector until you get to the
  827. the "scripts" section. Click the drop down and select "Load". Open your newly created ``RigidBody_hit_test.gd`` script.
  828. Final notes
  829. -----------
  830. .. image:: img/PartTwoFinished.png
  831. That was a lot of code! But now with all that done you can go give your weapons a test!
  832. You should now be able to fire as many bullets as you want on the cubes and
  833. they will move in response to the bullets colliding into them.
  834. In :ref:`doc_fps_tutorial_part_three`, we will add ammo to the weapons, as well as some sounds!
  835. .. warning:: If you ever get lost, be sure to read over the code again!
  836. You can download the finished project for this part here: :download:`Godot_FPS_Part_2.zip <files/Godot_FPS_Part_2.zip>`