part_two.rst 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002
  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 can 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. Let's get started!
  13. Making a system to handle animations
  14. ------------------------------------
  15. First we need a way to handle changing animations. Open up ``Player.tscn`` and select the :ref:`AnimationPlayer <class_AnimationPlayer>`
  16. Node (``Player`` -> ``Rotation_helper`` -> ``Model`` -> ``AnimationPlayer``).
  17. Create a new script called ``AnimationPlayer_Manager.gd`` and attach that to the :ref:`AnimationPlayer <class_AnimationPlayer>`.
  18. Add the following code to ``AnimationPlayer_Manager.gd``:
  19. ::
  20. extends AnimationPlayer
  21. # Structure -> Animation name :[Connecting Animation states]
  22. var states = {
  23. "Idle_unarmed":["Knife_equip", "Pistol_equip", "Rifle_equip", "Idle_unarmed"],
  24. "Pistol_equip":["Pistol_idle"],
  25. "Pistol_fire":["Pistol_idle"],
  26. "Pistol_idle":["Pistol_fire", "Pistol_reload", "Pistol_unequip", "Pistol_idle"],
  27. "Pistol_reload":["Pistol_idle"],
  28. "Pistol_unequip":["Idle_unarmed"],
  29. "Rifle_equip":["Rifle_idle"],
  30. "Rifle_fire":["Rifle_idle"],
  31. "Rifle_idle":["Rifle_fire", "Rifle_reload", "Rifle_unequip", "Rifle_idle"],
  32. "Rifle_reload":["Rifle_idle"],
  33. "Rifle_unequip":["Idle_unarmed"],
  34. "Knife_equip":["Knife_idle"],
  35. "Knife_fire":["Knife_idle"],
  36. "Knife_idle":["Knife_fire", "Knife_unequip", "Knife_idle"],
  37. "Knife_unequip":["Idle_unarmed"],
  38. }
  39. var animation_speeds = {
  40. "Idle_unarmed":1,
  41. "Pistol_equip":1.4,
  42. "Pistol_fire":1.8,
  43. "Pistol_idle":1,
  44. "Pistol_reload":1,
  45. "Pistol_unequip":1.4,
  46. "Rifle_equip":2,
  47. "Rifle_fire":6,
  48. "Rifle_idle":1,
  49. "Rifle_reload":1.45,
  50. "Rifle_unequip":2,
  51. "Knife_equip":1,
  52. "Knife_fire":1.35,
  53. "Knife_idle":1,
  54. "Knife_unequip":1,
  55. }
  56. var current_state = null
  57. var callback_function = null
  58. func _ready():
  59. set_animation("Idle_unarmed")
  60. connect("animation_finished", self, "animation_ended")
  61. func set_animation(animation_name):
  62. if animation_name == current_state:
  63. print ("AnimationPlayer_Manager.gd -- WARNING: animation is already ", animation_name)
  64. return true
  65. if has_animation(animation_name) == true:
  66. if current_state != null:
  67. var possible_animations = states[current_state]
  68. if animation_name in possible_animations:
  69. current_state = animation_name
  70. play(animation_name, -1, animation_speeds[animation_name])
  71. return true
  72. else:
  73. print ("AnimationPlayer_Manager.gd -- WARNING: Cannot change to ", animation_name, " from ", current_state)
  74. return false
  75. else:
  76. current_state = animation_name
  77. play(animation_name, -1, animation_speeds[animation_name])
  78. return true
  79. return false
  80. func animation_ended(anim_name):
  81. # UNARMED transitions
  82. if current_state == "Idle_unarmed":
  83. pass
  84. # KNIFE transitions
  85. elif current_state == "Knife_equip":
  86. set_animation("Knife_idle")
  87. elif current_state == "Knife_idle":
  88. pass
  89. elif current_state == "Knife_fire":
  90. set_animation("Knife_idle")
  91. elif current_state == "Knife_unequip":
  92. set_animation("Idle_unarmed")
  93. # PISTOL transitions
  94. elif current_state == "Pistol_equip":
  95. set_animation("Pistol_idle")
  96. elif current_state == "Pistol_idle":
  97. pass
  98. elif current_state == "Pistol_fire":
  99. set_animation("Pistol_idle")
  100. elif current_state == "Pistol_unequip":
  101. set_animation("Idle_unarmed")
  102. elif current_state == "Pistol_reload":
  103. set_animation("Pistol_idle")
  104. # RIFLE transitions
  105. elif current_state == "Rifle_equip":
  106. set_animation("Rifle_idle")
  107. elif current_state == "Rifle_idle":
  108. pass
  109. elif current_state == "Rifle_fire":
  110. set_animation("Rifle_idle")
  111. elif current_state == "Rifle_unequip":
  112. set_animation("Idle_unarmed")
  113. elif current_state == "Rifle_reload":
  114. set_animation("Rifle_idle")
  115. func animation_callback():
  116. if callback_function == null:
  117. print ("AnimationPlayer_Manager.gd -- WARNING: No callback function for the animation to call!")
  118. else:
  119. callback_function.call_func()
  120. Lets go over what this script is doing:
  121. _________
  122. Lets start with this script's global variables:
  123. - ``states``: A dictionary for holding our animation states. (Further explanation below)
  124. - ``animation_speeds``: A dictionary for holding all of the speeds we want to play our animations at.
  125. - ``current_state``: A variable for holding the name of the animation state we are currently in.
  126. - ``callback_function``: A variable for holding the callback function. (Further explanation below)
  127. If you are familiar with state machines, then you may have noticed that ``states`` is structured
  128. like a basic state machine. Here is roughly how ``states`` is set up:
  129. ``states`` is a dictionary with the key being the name of the current state, and the value being
  130. an array holding all of the states we can transition to. For example, if we are in currently in
  131. state ``Idle_unarmed``, we can only transition to ``Knife_equip``, ``Pistol_equip``, ``Rifle_equip``, and
  132. ``Idle_unarmed``.
  133. If we try to transition to a state that is not included in our possible transitions states,
  134. then we get a warning message and the animation does not change. We will also automatically
  135. transition from some states into others, as will be explained further below in ``animation_ended``
  136. .. note:: For the sake of keeping this tutorial simple we are not using a 'proper'
  137. state machine. If you are interested to know more about state machines,
  138. see the following articles:
  139. - (Python example) https://dev.to/karn/building-a-simple-state-machine-in-python
  140. - (C# example) https://www.codeproject.com/Articles/489136/UnderstandingplusandplusImplementingplusStateplusP
  141. - (Wiki article) https://en.wikipedia.org/wiki/Finite-state_machine
  142. In a future part of this tutorial series we may revise this script to include a proper 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 smooth, we need to play them at faster speeds than some
  145. of the others.
  146. -- note:: Notice that all of the firing animations are faster than their normal speed. Remember this for later!
  147. ``current_state`` will hold the name of the animation state we are currently in.
  148. Finally, ``callback_function`` will be a :ref:`FuncRef <class_FuncRef>` passed in by our player for spawning bullets
  149. at the proper frame of animation. A :ref:`FuncRef <class_FuncRef>` allows us to pass in a function as an argument,
  150. effectively allowing us to call a function from another script, which is how we will use it later.
  151. _________
  152. Now lets look at ``_ready``. First we are setting our animation to ``Idle_unarmed``, using the ``set_animation`` function,
  153. so we for sure start in that animation. Next we connect the ``animation_finished`` signal to this script and assign
  154. it to call ``animation_ended``.
  155. _________
  156. Lets look at ``set_animation`` next.
  157. ``set_animation`` sets the animation to the that of the passed in
  158. animation state *if* we can transition to it. In other words, if the animation state we are currently in
  159. has the passed in animation state name in ``states``, then we will change to that animation.
  160. First we check if the passed in animation is the same as the animation state we are currently in.
  161. If it is, then we write a warning to the console and return ``true``.
  162. Next we see if :ref:`AnimationPlayer <class_AnimationPlayer>` has the passed in animation using ``has_animation``. If it does not, we return ``false``.
  163. Then we check if ``current_state`` is set or not. If ``current_state`` is *not* currently set, we
  164. set ``current_state`` to the passed in animation and tell :ref:`AnimationPlayer <class_AnimationPlayer>` to start playing the animation with
  165. a blend time of ``-1`` and at the speed set in ``animation_speeds`` and then we return ``true``.
  166. If we have a state in ``current_state``, then we get all of the possible states we can transition to.
  167. If the animation name is in the array of possible transitions, then we set ``current_state`` to the passed
  168. in animation, tell :ref:`AnimationPlayer <class_AnimationPlayer>` to play the animation with a blend time of ``-1`` at the speed set in ``animation_speeds``
  169. and then we return ``true``.
  170. _________
  171. Now lets look at ``animation_ended``.
  172. ``animation_ended`` is the function that will be called by :ref:`AnimationPlayer <class_AnimationPlayer>` when it's done playing a animation.
  173. For certain animation states, we may need to transition into another state when its finished. To handle this, we
  174. check for every possible animation state. If we need to, we transition into another state.
  175. .. warning:: If you are using your own animated models, make sure that none of the animations are set
  176. to loop. Looping animations do not send the ``animation_finished`` signal when they reach
  177. the end of the animation and are about to loop.
  178. .. note:: the transitions in ``animation_ended`` ideally would be part of the data in ``states``, but in
  179. an effort to make the tutorial easier to understand, we'll just hard code each state transition
  180. in ``animation_ended``.
  181. _________
  182. Finally we have ``animation_callback``. This function will be called by a function track in our animations.
  183. If we have a :ref:`FuncRef <class_FuncRef>` assigned to ``callback_function``, then we call that passed in function. If we do not
  184. have a :ref:`FuncRef <class_FuncRef>` assigned to ``callback_function``, we print out a warning to the console.
  185. .. tip:: Try running ``Testing_Area.tscn`` just to make sure there is no runtime issues. If the game runs but nothing
  186. seems to have changed, then everything is working correctly.
  187. Getting the animations ready
  188. ----------------------------
  189. Now that we have a working animation manager, we need to call it from our player script.
  190. Before that though, we need to set some animation callback tracks in our firing animations.
  191. Open up ``Player.tscn`` if you don't have it open and navigate to the :ref:`AnimationPlayer <class_AnimationPlayer>` node
  192. (``Player`` -> ``Rotation_helper`` -> ``Model`` -> ``AnimationPlayer``).
  193. We need to attach a function track to three of our animations: The firing animation for the pistol, rifle, and knife.
  194. Let's start with the pistol. Click the animation drop down list and select "Pistol_fire".
  195. Now scroll down to the very bottom of the list of animation tracks. The final item in the list should read
  196. ``Armature/Skeleton:Left_UpperPointer``. Now at the bottom of the list, click the plus icon on the bottom
  197. bar of animation window, right next to the loop button and the up arrow.
  198. .. image:: img/AnimationPlayerAddTrack.png
  199. This will bring up a window with three choices. We're wanting to add a function callback track, so click the
  200. option that reads "Add Call Func Track". This will open a window showing the entire node tree. Navigate to the
  201. :ref:`AnimationPlayer <class_AnimationPlayer>` node, select it, and press OK.
  202. .. image:: img/AnimationPlayerCallFuncTrack.png
  203. Now at the bottom of list of animation tracks you will have a green track that reads "AnimationPlayer".
  204. Now we need to add the point where we want to call our callback function. Scrub the timeline until you
  205. reach the point where the muzzle just starts to flash.
  206. .. note:: The timeline is the window where all of the points in our animation are stored. Each of the little
  207. points represents a point of animation data.
  208. Scrubbing the timeline means moving ourselves through the animation. So when we say "scrub the timeline
  209. until you reach a point", what we mean is move through the animation window until you reach the a point
  210. on the timeline.
  211. Also, the muzzle of a gun is the end point where the bullet comes out. The muzzle flash is the flash of
  212. light that escapes the muzzle when a bullet is fired. The muzzle is also sometimes referred to as the
  213. barrel of the gun.
  214. .. tip:: For finer control when scrubbing the timeline, press ``control`` and scroll forwards with the mouse wheel to zoom in.
  215. Scrolling backwards will zoom out.
  216. You can also change how the timeline scrubbing snaps by changing the value in ``Step (s)`` to a lower/higher value.
  217. Once you get to a point you like, press the little green plus symbol on the far right side of the
  218. ``AnimationPlayer`` track. This will place a little green point at the position you are currently
  219. at in the animation on your ``AnimationPlayer`` track.
  220. .. image:: img/AnimationPlayerAddPoint.png
  221. Now we have one more step before we are done with the pistol. Select the "enable editing of individual keys"
  222. button on the far right corner of the animation window. It looks like a pencil with a little point beside it.
  223. .. image:: img/AnimationPlayerEditPoints.png
  224. Once you've click that, a new window will open on the right side. Now click the green point on the ``AnimationPlayer``
  225. track. This will bring up the information associated with that point in the timeline. In the empty name field, enter
  226. "animation_callback" and press ``enter``.
  227. Now when we are playing this animation the callback function will be triggered at that specific point of the animation.
  228. .. warning:: Be sure to press the "enable editing of individual keys" button again to turn off the ability to edit individual keys
  229. so you cannot change one of the transform tracks by accident!
  230. _________
  231. Let's repeat the process for the rifle and knife firing animations!
  232. .. note:: Because the process is exactly the same as the pistol, the process is going to explained in a little less depth.
  233. Follow the steps in the above if you get lost! It is exactly the same, just on a different animation.
  234. Go to the "Rifle_fire" animation from the animation drop down. Add the function callback track once you reach the bottom of the
  235. animation track list by clicking the little plus icon at the bottom of the screen. Find the point where the muzzle just starts
  236. to flash and click the little green plus symbol to add a function callback point at that position on the track.
  237. Next, click the "enable editing of individual keys" button.
  238. Select the newly created function callback point, put "animation_callback" into the name field and press ``enter``.
  239. Click the "enable editing of individual keys" button again to turn off individual key editing.
  240. so we cannot change one of the transform tracks by accident.
  241. Now we just need to apply the callback function track to the knife animation. Select the "Knife_fire" animation and scroll to the bottom of the
  242. animation tracks. Click the plus symbol at the bottom of the animation window and add a function callback track.
  243. Next find a point around the first third of the animation to place the animation callback function point at.
  244. .. note:: We will not actually be firing the knife, and the animation really is a stabbing animation rather than a firing one.
  245. For this tutorial we are just reusing the gun firing logic for our knife, so the animation has been named in a style that
  246. is consistent with the other animations.
  247. 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"
  248. button, the button with a plus at the bottom right side of the animation window.
  249. Select the newly created function callback point, put "animation_callback" into the name field and press ``enter``.
  250. Click the "enable editing of individual keys" button again to turn off individual key editing.
  251. so we cannot change one of the transform tracks by accident.
  252. .. tip:: Be sure to save your work!
  253. With that done, we are almost ready to start adding the ability to fire to our player script! We just need to setup one last scene:
  254. The scene for our bullet object.
  255. Creating the bullet scene
  256. -------------------------
  257. There are several ways to handle a gun's bullets in video games. In this tutorial series,
  258. we will be exploring two of the more common ways: Objects, and raycasts.
  259. _________
  260. One of the two ways is using a bullet object. This will be an object that travels through the world and handles
  261. its own collision code. This method we create/spawn a bullet object in the direction our gun is facing, and then
  262. it sends itself forward.
  263. 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
  264. 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.
  265. 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
  266. 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 just instantly
  267. hit whatever its pointed at. This feels more realistic because nothing in real life really moves instantly from one point to another.
  268. 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,
  269. 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
  270. bullets, it can become a huge problem when you potentially have several hundred bullets.
  271. Despite the performance hit, many first person shooters include some form of object bullets. Rocket launchers are a prime example because in many
  272. first person shooters, Rockets do not just instantly explode at their target position. You can also find bullets as object many times with grenades
  273. because they generally bounce around the world before exploding.
  274. .. note:: While I cannot say for sure this is the case, these games *probably* use bullet objects in some form or another:
  275. (These are entirely from my observations. **They may be entirely wrong**. I have never worked on **any** of the following games)
  276. - Halo (Rocket launchers, fragment grenades, sniper rifles, brute shot, and more)
  277. - Destiny (Rocket launchers, grenades, fusion rifles, sniper rifles, super moves, and more)
  278. - Call of Duty (Rocket launchers, grenades, ballistic knives, crossbows, and more)
  279. - Battlefield (Rocket launchers, grenades, claymores, mortars, and more)
  280. Another disadvantage with bullet objects is networking. Bullet objects have to sync the positions (at least) with however many clients are connected
  281. to the server.
  282. While we are not implementing any form of networking (as that would be it's own entire tutorial series), it is a consideration
  283. to keep in mind when creating your first person shooter, especially if you plan on adding some form of networking in the future.
  284. _________
  285. The other way of handling bullet collisions we will be looking at, is raycasting.
  286. This method is extremely common in guns that have fast moving bullets that rarely change trajectory change over time.
  287. 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.
  288. 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.
  289. .. note:: While I cannot say for sure this is the case, these games *probably* use raycasts in some form or another:
  290. (These are entirely from my observations. **They may be entirely wrong**. I have never worked on **any** of the following games)
  291. - Halo (Assault rifles, DMRs, battle rifles, covenant carbine, spartan laser, and more)
  292. - Destiny (Auto rifles, pulse rifles, scout rifles, hand cannons, machine guns, and more)
  293. - Call of Duty (Assault rifles, light machine guns, sub machine guns, pistols, and more)
  294. - Battlefield (Assault rifles, SMGs, carbines, pistols, and more)
  295. One huge advantage for this method is it's really light on performance.
  296. Sending a couple hundred rays through space is *way* easier for the computer to calculate than sending a couple hundred
  297. bullet objects.
  298. 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
  299. to sync the bullet movements over the Internet, we just need to send whether or not the raycast hit.
  300. Raycasting does have some disadvantages though. One major disadvantage is we cannot easily cast a ray in anything but a linear line.
  301. 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
  302. multiple rays at different positions, but not only is this hard to implement in code, it is also is heavier on performance.
  303. 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
  304. to it, but because raycasts happen instantly, we do not really have a decent way of showing the bullets. You could draw a line from the origin of the
  305. 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
  306. at all, because theoretically the bullets move so fast our eyes could not see it anyway.
  307. _________
  308. Lets get the bullet object setup. This is what our pistol will create when the "Pistol_fire" animation callback function is called.
  309. Open up ``Bullet_Scene.tscn``. The scene contains :ref:`Spatial <class_Spatial>` node called bullet, with a :ref:`MeshInstance <class_MeshInstance>`
  310. and an :ref:`Area <class_Area>` with a :ref:`CollisionShape <class_CollisionShape>` childed to it.
  311. Create a new script called ``Bullet_script.gd`` and attach it to the ``Bullet`` :ref:`Spatial <class_Spatial>`.
  312. 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
  313. .. 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>`
  314. is because we do not want the bullet to interact with other :ref:`RigidBody <class_RigidBody>` nodes.
  315. 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.
  316. Another reason is simply because it is easier to detect collisions with a :ref:`Area <class_Area>`!
  317. Here's the script that will control our bullet:
  318. ::
  319. extends Spatial
  320. const BULLET_SPEED = 80
  321. const BULLET_DAMAGE = 15
  322. const KILL_TIMER = 4
  323. var timer = 0
  324. var hit_something = false
  325. func _ready():
  326. get_node("Area").connect("body_entered", self, "collided")
  327. set_physics_process(true)
  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 traveling forever. By using a kill timer, we can assure that
  352. no bullets will just travel forever and consume resources.
  353. _________
  354. In ``_ready`` we set the area's ``body_entered`` signal to ourself so that it calls
  355. the ``collided`` function. Then we set ``_physics_process`` to ``true``.
  356. _________
  357. ``_physics_process`` gets the bullet's local ``Z`` axis. If you look in at the scene
  358. in local mode, you will find that the bullet faces the positive local ``Z`` axis.
  359. Next we translate the entire bullet by that forward direction, multiplying in our speed and delta time.
  360. After that we add delta time to our timer and check if the timer has as long or longer
  361. than our ``KILL_TIME`` constant. If it has, we use ``queue_free`` to free ourselves.
  362. _________
  363. In ``collided`` we check if we've hit something yet or not.
  364. Remember that ``collided`` is
  365. only called when a body has entered the :ref:`Area <class_Area>` node. If we have not already collided with
  366. something, we then proceed to check if the body we've collided with has a function/method
  367. called ``bullet_hit``. If it does, we call it and pass in our damage and our position.
  368. .. note:: in ``collided``, the passed in body can be a :ref:`StaticBody <class_StaticBody>`,
  369. :ref:`RigidBody <class_RigidBody>`, or :ref:`KinematicBody <class_KinematicBody>`
  370. Then we set ``hit_something`` to ``true`` because regardless of whether or not the body
  371. the bullet collided with has the ``bullet_hit`` function/method, it has hit something.
  372. Then we free the bullet using ``queue_free``.
  373. .. tip:: You may be wondering why we even have a ``hit_something`` variable if we
  374. free the bullet using ``queue_free`` as soon as it hits something.
  375. The reason we need to track whether we've hit something or not is because ``queue_free``
  376. does not immediately free the node, so the bullet could collide with another body
  377. before Godot has a chance to free it. By tracking if the bullet has hit something
  378. we can make sure that the bullet will only hit one object.
  379. _________
  380. Before we start programming the player again, let's take a quick look at ``Player.tscn``.
  381. Open up ``Player.tscn`` again.
  382. Expand ``Rotation_helper`` and notice how it has two nodes: ``Gun_fire_points`` and
  383. ``Gun_aim_point``.
  384. ``Gun_aim_point`` is the point that the bullets will be aiming at. Notice how it
  385. is lined up with the center of the screen and pulled a distance forward on the Z
  386. axis. ``Gun_aim_point`` will serve as the point where the bullets will for sure collide
  387. with as it goes along.
  388. .. note:: There is a invisible mesh instance for debugging purposes. The mesh is
  389. a small sphere that visually shows where the bullets will be aiming at.
  390. Open up ``Gun_fire_points`` and you'll find three more :ref:`Spatial <class_Spatial>` nodes, one for each
  391. weapon.
  392. Open up ``Rifle_point`` and you'll find a :ref:`Raycast <class_Raycast>` node. This is where
  393. we will be sending the raycasts for our rilfe's bullets.
  394. The length of the raycast will dictate how far our the bullets will travel.
  395. We are using a :ref:`Raycast <class_Raycast>` node to handle the rifle's bullet because
  396. we want to fire lots of bullets quickly. If we use bullet objects, it is quite possible
  397. we could run into performance issues on older machines.
  398. .. note:: If you are wondering where the positions of the points came from, they
  399. are the rough positions of the ends of each weapon. You can see this by
  400. going to ``AnimationPlayer``, selecting one of the firing animations
  401. and scrubbing through the timeline. The point for each weapon should mostly line
  402. up with the end of each weapon.
  403. 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
  404. because we only care for all of the bodies close to us, and because our knife does
  405. not fire into space. If we were making a throwing knife, we would likely spawn a bullet
  406. object that looks like a knife.
  407. Finally, we have ``Pistol point``. This is the point where we will be creating/instancing
  408. our bullet objects. We do not need any additional nodes here, as the bullet handles all
  409. of its own collision detection.
  410. Now that we've seen how we will handle our other weapons, and where we will spawn the bullets,
  411. let's start working on making them work.
  412. .. note:: You can also look at the HUD nodes if you want. There is nothing fancy there and other
  413. than using a single :ref:`Label <class_Label>`, we will not be touching any of those nodes.
  414. Check :ref:`doc_design_interfaces_with_the_control_nodes` for a tutorial on using GUI nodes.
  415. The GUI provided in this tutorial is *very* basic. Maybe in a later part we will
  416. revise the GUI, but for now we are going to just use this GUI as it will serve our needs for now.
  417. Making the weapons work
  418. -----------------------
  419. Lets start making the weapons work in ``Player.gd``.
  420. First lets start by adding some global variables we'll need for the weapons:
  421. ::
  422. # Place before _ready
  423. var animation_manager;
  424. var current_gun = "UNARMED"
  425. var changing_gun = false
  426. var bullet_scene = preload("Bullet_Scene.tscn")
  427. var health = 100
  428. const RIFLE_DAMAGE = 4
  429. const KNIFE_DAMAGE = 40
  430. var UI_status_label
  431. Let's go over what these new variables will do:
  432. - ``animation_manager``: This will hold the :ref:`AnimationPlayer <class_AnimationPlayer>` node and its script, which we wrote previously.
  433. - ``current_gun``: This is the name of the gun we are currently using. It has four possible values: ``UNARMED``, ``KNIFE``, ``PISTOL``, and ``RIFLE``.
  434. - ``changing_gun``: A boolean to track whether or not we are changing guns/weapons.
  435. - ``bullet_scene``: The bullet scene we worked on earlier, ``Bullet_Scene.tscn``. We need to load it here so we can create/spawn it when the pistol fires
  436. - ``health``: How much health our player has. In this part of the tutorial we will not really be using it.
  437. - ``RIFLE_DAMAGE``: How much damage a single rifle bullet causes.
  438. - ``KNIFE_DAMAGE``: How much damage a single knife stab/swipe causes.
  439. - ``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.
  440. _________
  441. Next we need to add a few things in ``_ready``. Here's the new ``_ready`` function:
  442. ::
  443. func _ready():
  444. camera = get_node("Rotation_helper/Camera")
  445. camera_holder = get_node("Rotation_helper")
  446. animation_manager = get_node("Rotation_helper/Model/AnimationPlayer")
  447. animation_manager.callback_function = funcref(self, "fire_bullet")
  448. set_physics_process(true)
  449. Input.set_mouse_mode(Input.MOUSE_MODE_CAPTURED)
  450. set_process_input(true)
  451. # Make sure the bullet spawn point, the raycast, and the knife area are all aiming at the center of the screen
  452. var gun_aim_point_pos = get_node("Rotation_helper/Gun_aim_point").global_transform.origin
  453. get_node("Rotation_helper/Gun_fire_points/Pistol_point").look_at(gun_aim_point_pos, Vector3(0, 1, 0))
  454. get_node("Rotation_helper/Gun_fire_points/Rifle_point").look_at(gun_aim_point_pos, Vector3(0, 1, 0))
  455. get_node("Rotation_helper/Gun_fire_points/Knife_point").look_at(gun_aim_point_pos, Vector3(0, 1, 0))
  456. # Because we have the camera rotated by 180 degrees, we need to rotate the points around by 180
  457. # degrees on their local Y axis because otherwise the bullets will fire backwards
  458. get_node("Rotation_helper/Gun_fire_points/Pistol_point").rotate_object_local(Vector3(0, 1, 0), deg2rad(180))
  459. get_node("Rotation_helper/Gun_fire_points/Rifle_point").rotate_object_local(Vector3(0, 1, 0), deg2rad(180))
  460. get_node("Rotation_helper/Gun_fire_points/Knife_point").rotate_object_local(Vector3(0, 1, 0), deg2rad(180))
  461. UI_status_label = get_node("HUD/Panel/Gun_label")
  462. flashlight = get_node("Rotation_helper/Flashlight")
  463. Let's go over what's changed.
  464. First we get the :ref:`AnimationPlayer <class_AnimationPlayer>` node and assign it to our animation_manager variable. Then we set the callback function
  465. 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,
  466. but we'll get there soon.
  467. Then we get all of the weapon points and call each of their ``look_at``.
  468. This will make sure they all are facing the gun aim point, which is in the center of our camera at a certain distance back.
  469. Next we rotate all of those weapon points by ``180`` degrees on their ``Y`` axis. This is because our camera is pointing backwards.
  470. If we did not rotate all of these weapon points by ``180`` degrees, all of the weapons would fire backwards at ourselves.
  471. Finally, we get the UI :ref:`Label <class_Label>` from our HUD.
  472. _________
  473. Lets add a few things to ``_physics_process`` so we can fire our weapons. Here's the new code:
  474. ::
  475. func _physics_process(delta):
  476. var dir = Vector3()
  477. var cam_xform = camera.get_global_transform()
  478. if Input.is_action_pressed("movement_forward"):
  479. dir += -cam_xform.basis.z.normalized()
  480. if Input.is_action_pressed("movement_backward"):
  481. dir += cam_xform.basis.z.normalized()
  482. if Input.is_action_pressed("movement_left"):
  483. dir += -cam_xform.basis.x.normalized()
  484. if Input.is_action_pressed("movement_right"):
  485. dir += cam_xform.basis.x.normalized()
  486. if is_on_floor():
  487. if Input.is_action_just_pressed("movement_jump"):
  488. vel.y = JUMP_SPEED
  489. if Input.is_action_just_pressed("flashlight"):
  490. if flashlight.is_visible_in_tree():
  491. flashlight.hide()
  492. else:
  493. flashlight.show()
  494. if Input.is_action_pressed("movement_sprint"):
  495. is_sprinting = true;
  496. else:
  497. is_sprinting = false;
  498. dir.y = 0
  499. dir = dir.normalized()
  500. var grav = norm_grav
  501. vel.y += delta*grav
  502. var hvel = vel
  503. hvel.y = 0
  504. var target = dir
  505. if is_sprinting:
  506. target *= MAX_SPRINT_SPEED
  507. else:
  508. target *= MAX_SPEED
  509. var accel
  510. if dir.dot(hvel) > 0:
  511. if is_sprinting:
  512. accel = SPRINT_ACCEL
  513. else:
  514. accel = ACCEL
  515. else:
  516. accel = DEACCEL
  517. hvel = hvel.linear_interpolate(target, accel*delta)
  518. vel.x = hvel.x
  519. vel.z = hvel.z
  520. vel = move_and_slide(vel,Vector3(0,1,0), 0.05, 4, deg2rad(MAX_SLOPE_ANGLE))
  521. if Input.is_action_just_pressed("ui_cancel"):
  522. if Input.get_mouse_mode() == Input.MOUSE_MODE_VISIBLE:
  523. Input.set_mouse_mode(Input.MOUSE_MODE_CAPTURED)
  524. else:
  525. Input.set_mouse_mode(Input.MOUSE_MODE_VISIBLE)
  526. # NEW CODE
  527. if changing_gun == false:
  528. if Input.is_key_pressed(KEY_1):
  529. current_gun = "UNARMED"
  530. changing_gun = true
  531. elif Input.is_key_pressed(KEY_2):
  532. current_gun = "KNIFE"
  533. changing_gun = true
  534. elif Input.is_key_pressed(KEY_3):
  535. current_gun = "PISTOL"
  536. changing_gun = true
  537. elif Input.is_key_pressed(KEY_4):
  538. current_gun = "RIFLE"
  539. changing_gun = true
  540. if changing_gun == true:
  541. if current_gun != "PISTOL":
  542. if animation_manager.current_state == "Pistol_idle":
  543. animation_manager.set_animation("Pistol_unequip")
  544. if current_gun != "RIFLE":
  545. if animation_manager.current_state == "Rifle_idle":
  546. animation_manager.set_animation("Rifle_unequip")
  547. if current_gun != "KNIFE":
  548. if animation_manager.current_state == "Knife_idle":
  549. animation_manager.set_animation("Knife_unequip")
  550. if current_gun == "UNARMED":
  551. if animation_manager.current_state == "Idle_unarmed":
  552. changing_gun = false
  553. elif current_gun == "KNIFE":
  554. if animation_manager.current_state == "Knife_idle":
  555. changing_gun = false
  556. if animation_manager.current_state == "Idle_unarmed":
  557. animation_manager.set_animation("Knife_equip")
  558. elif current_gun == "PISTOL":
  559. if animation_manager.current_state == "Pistol_idle":
  560. changing_gun = false
  561. if animation_manager.current_state == "Idle_unarmed":
  562. animation_manager.set_animation("Pistol_equip")
  563. elif current_gun == "RIFLE":
  564. if animation_manager.current_state == "Rifle_idle":
  565. changing_gun = false
  566. if animation_manager.current_state == "Idle_unarmed":
  567. animation_manager.set_animation("Rifle_equip")
  568. # Firing the weapons
  569. if Input.is_action_pressed("fire"):
  570. if current_gun == "PISTOL":
  571. if animation_manager.current_state == "Pistol_idle":
  572. animation_manager.set_animation("Pistol_fire")
  573. elif current_gun == "RIFLE":
  574. if animation_manager.current_state == "Rifle_idle":
  575. animation_manager.set_animation("Rifle_fire")
  576. elif current_gun == "KNIFE":
  577. if animation_manager.current_state == "Knife_idle":
  578. animation_manager.set_animation("Knife_fire")
  579. # HUD (UI)
  580. UI_status_label.text = "HEALTH: " + str(health)
  581. Lets go over it one chunk at a time:
  582. _________
  583. First we have an if check to see if ``changing_gun`` is equal to ``false``. If it is, we
  584. then check to see if the number keys ``1`` through ``4`` are pressed. If one of the keys
  585. are pressed, we set current gun to the name of each weapon assigned to each key and set
  586. ``changing_gun`` to ``true``.
  587. Then we check if ``changing_gun`` is ``true``. If it is ``true``, we then go through a series of checks.
  588. The first set of checks is checking if we are in a idle animation that is not the weapon/gun we are trying
  589. to change to, as then we'd be stuck in a loop.
  590. Then we check if we are in an unarmed state. If we are and the newly selected 'weapon'
  591. is ``UNARMED``, then we set ``changing_gun`` to ``false``.
  592. If we are trying to change to any of the other weapons, we first check if we are in the
  593. desired weapon's idle state. If we are, then we've successfully changed weapons and set
  594. ``changing_gun`` to false.
  595. If we are not in the desired weapon's idle state, we then check if we are in the idle unarmed state.
  596. This is because all unequip animations transition to idle unarmed, and because we can transition to
  597. any equip animation from idle unarmed.
  598. If we are in the idle unarmed state, we set the animation to the equip animation for the
  599. desired weapon. Once the equip animation is finished, it will change to the idle state for that
  600. weapon, which will pass the ``if`` check above.
  601. _________
  602. For firing the weapons we first check if the ``fire`` action is pressed or not.
  603. If the fire action is pressed, we then check which weapon we are using.
  604. If we are in a weapon's idle state, we then call set the animation to the weapon's fire animation.
  605. _________
  606. Now, we just need to add one more function to the player, and then the player is ready to start shooting!
  607. We just need to add ``fire_bullet``, which will be called when by the :ref:`AnimationPlayer <class_AnimationPlayer>` at those
  608. points we set earlier in the :ref:`AnimationPlayer <class_AnimationPlayer>` function track:
  609. ::
  610. func fire_bullet():
  611. if changing_gun == true:
  612. return
  613. # Pistol bullet handling: Spawn a bullet object!
  614. if current_gun == "PISTOL":
  615. var clone = bullet_scene.instance()
  616. var scene_root = get_tree().root.get_children()[0]
  617. scene_root.add_child(clone)
  618. clone.global_transform = get_node("Rotation_helper/Gun_fire_points/Pistol_point").global_transform
  619. # The bullet is a little too small (by default), so let's make it bigger!
  620. clone.scale = Vector3(4, 4, 4)
  621. # Rifle bullet handeling: Send a raycast!
  622. elif current_gun == "RIFLE":
  623. var ray = get_node("Rotation_helper/Gun_fire_points/Rifle_point/RayCast")
  624. ray.force_raycast_update()
  625. if ray.is_colliding():
  626. var body = ray.get_collider()
  627. if body.has_method("bullet_hit"):
  628. body.bullet_hit(RIFLE_DAMAGE, ray.get_collision_point())
  629. # Knife bullet(?) handeling: Use an area!
  630. elif current_gun == "KNIFE":
  631. var area = get_node("Rotation_helper/Gun_fire_points/Knife_point/Area")
  632. var bodies = area.get_overlapping_bodies()
  633. for body in bodies:
  634. if body.has_method("bullet_hit"):
  635. body.bullet_hit(KNIFE_DAMAGE, area.global_transform.origin)
  636. Lets go over what this function is doing:
  637. _________
  638. First we check if we are changing weapons or not. If we are changing weapons, we do not want shoot so we just ``return``.
  639. .. tip:: Calling ``return`` stops the rest of the function from being called. In this case, we are not returning a variable
  640. because we are only interested in not running the rest of the code, and because we are not looking for a returned
  641. variable either when we call this function.
  642. Next we check which weapon we are using.
  643. If we are using a pistol, we first create a ``Bullet_Scene.tscn`` instance and assign it to
  644. a variable named ``clone``. Then we get the root node in the :ref:`SceneTree <class_SceneTree>`, which happens to be a :ref:`Viewport <class_Viewport>`.
  645. We then get the first child of the :ref:`Viewport <class_Viewport>` and assign it to the ``scene_root`` variable.
  646. We then add our newly instanced/created bullet as a child of ``scene_root``.
  647. .. warning:: As mentioned later below in the section on adding sounds, this method makes a assumption. This will be explained later
  648. in the section on adding sounds in :ref:`doc_fps_tutorial_part_three`
  649. Next we set the global :ref:`Transform <class_Transform>` of the bullet to that of the pistol bullet spawn point we
  650. talked about earlier.
  651. Finally, we set the scale a little bigger because the bullet normally is too small to see.
  652. _______
  653. For the rifle, we first get the :ref:`Raycast <class_Raycast>` node and assign it to a variable called ``ray``.
  654. Then we call :ref:`Raycast <class_Raycast>`'s ``force_raycast_update`` function.
  655. ``force_raycast_update`` sends the :ref:`Raycast <class_Raycast>` out and collects the collision data as soon as we call it,
  656. meaning we get frame perfect collision data and we do not need to worry about performance issues by having the
  657. :ref:`Raycast <class_Raycast>` enabled all the time.
  658. Next we check if the :ref:`Raycast <class_Raycast>` collided with anything. If it has, we then get the collision body
  659. it collided with. If the body has the ``bullet_hit`` method/function, we then call it and pass
  660. in ``RIFLE_DAMAGE`` and the position where the :ref:`Raycast <class_Raycast>` collided.
  661. .. tip:: Remember how we mentioned the speed of the animations for firing was faster than
  662. the other animations? By changing the firing animation speeds, you can change how
  663. fast the weapon fires bullets!
  664. _______
  665. For the knife we first get the :ref:`Area <class_Area>` node and assign it to a variable named ``area``.
  666. Then we get all of the collision bodies inside the :ref:`Area <class_Area>`. We loop through each one
  667. and check if they have the ``bullet_hit`` method/function. If they do, we call it and pass
  668. in ``KNIFE_DAMAGE`` and the global position of :ref:`Area <class_Area>`.
  669. .. note:: While we could attempt to calculate a rough location for where the knife hit, we
  670. do not bother because using the area's position works well enough and the extra time
  671. needed to calculate a rough position for each body is not really worth the effort.
  672. _______
  673. Before we are ready to test our new weapons, we still have just a little bit of work to do.
  674. Creating some test subjects
  675. ---------------------------
  676. Create a new script by going to the scripting window, clicking "file", and selecting new.
  677. Name this script "RigidBody_hit_test" and make sure it extends :ref:`RigidBody <class_RigidBody>`.
  678. Now we just need to add this code:
  679. ::
  680. extends RigidBody
  681. func _ready():
  682. pass
  683. func bullet_hit(damage, bullet_hit_pos):
  684. var direction_vect = self.global_transform.origin - bullet_hit_pos
  685. direction_vect = direction_vect.normalized()
  686. self.apply_impulse(bullet_hit_pos, direction_vect * damage)
  687. Lets go over how ``bullet_hit`` works:
  688. First we get the direction from the bullet pointing towards our global :ref:`Transform <class_Transform>`.
  689. We do this by subtracting the bullet's hit position from the :ref:`RigidBody <class_RigidBody>`'s position.
  690. This results in a :ref:`Vector3 <class_Vector3>` that we can use to tell the direction the bullet collided into the
  691. :ref:`RigidBody <class_RigidBody>` at.
  692. We then normalize it so we do not get crazy results from collisions on the extremes
  693. of the collision shape attached to the :ref:`RigidBody <class_RigidBody>`. Without normalizing shots farther
  694. away from the center of the :ref:`RigidBody <class_RigidBody>` would cause a more noticeable reaction than
  695. those closer to the center.
  696. Finally, we apply an impulse at the passed in bullet collision position. With the force
  697. being the directional vector times the damage the bullet is supposed to cause. This makes
  698. the :ref:`RigidBody <class_RigidBody>` seem to move in response to the bullet colliding into it.
  699. _______
  700. Now we just need to attach this script to all of the :ref:`RigidBody <class_RigidBody>` nodes we want to effect.
  701. Open up ``Testing_Area.tscn`` and select all of the cubes parented to the ``Cubes`` node.
  702. .. tip:: If you select the top cube, and then hold down ``shift`` and select the last cube, Godot will
  703. select all of the cubes in between!
  704. Once you have all of the cubes selected, scroll down in the inspector until you get to the
  705. the "scripts" section. Click the drop down and select "Load". Open your newly created ``RigidBody_hit_test.gd`` script.
  706. With that done, go give your guns a whirl! You should now be able to fire as many bullets as you want on the cubes and
  707. they will move in response to the bullets colliding into them.
  708. In :ref:`doc_fps_tutorial_part_three`, we will add ammo to the guns, as well as some sounds!