2
0

part_one.rst 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644
  1. .. _doc_fps_tutorial_part_one:
  2. Part 1
  3. ======
  4. Tutorial introduction
  5. ---------------------
  6. .. image:: img/FinishedTutorialPicture.png
  7. This tutorial series will show you how to make a single player FPS game.
  8. Throughout the course of this tutorial series, we will cover how:
  9. - To make a first person character that can move, sprint, and jump.
  10. - To make a simple animation state machine for handling animation transitions.
  11. - To add three weapons to the first person character, each using a different way to handle bullet collisions:
  12. - - A knife (using an :ref:`Area <class_Area>`)
  13. - - A pistol (Bullet scenes)
  14. - - A rifle (using a :ref:`Raycast <class_Raycast>`)
  15. - To add two different types of grenades to the first person character:
  16. - - A normal grenade
  17. - - A sticky grenade
  18. - To add the ability to grab and throw :ref:`RigidBody <class_RigidBody>` nodes
  19. - To add joypad input for the player
  20. - To add ammo and reloading for all weapons that consume ammo.
  21. - To add ammo and health pick ups
  22. - - In two sizes: big and small
  23. - To add an automatic turret
  24. - - That can fire using bullet objects or a :ref:`Raycast <class_Raycast>`
  25. - To add targets that break when they've taken enough damage
  26. - To add sounds that play when the guns fire.
  27. - To add a simple main menu:
  28. - - With an options menu for changing how the game runs
  29. - - With a level select screen
  30. - To add a universal pause menu we can access anywhere
  31. .. note:: While this tutorial can be completed by beginners, it is highly
  32. advised to complete :ref:`doc_your_first_game`,
  33. if you are new to Godot and/or game development **before** going through
  34. this tutorial series.
  35. Remember: Making 3D games is much harder than making 2D games. If you do not know
  36. how to make 2D games you will likely struggle making 3D games.
  37. This tutorial assumes you know have experience working with the Godot editor,
  38. have basic programming experience in GDScript, and have basic experience in game development.
  39. You can find the start assets for this tutorial here: :download:`Godot_FPS_Starter.zip <files/Godot_FPS_Starter.zip>`
  40. The provided starter assets contain an animated 3D model, a bunch of 3D models for making levels,
  41. and a few scenes already configured for this tutorial.
  42. All assets provided (unless otherwise noted) were originally created by TwistedTwigleg, with changes/additions by the Godot community.
  43. All original assets provided for this tutorial are released under the ``MIT`` license.
  44. Feel free to use these assets however you want! All original assets belong to the Godot community, with the other assets belonging to those listed below:
  45. .. note:: The skybox is created by **StumpyStrust** on OpenGameArt. The skybox used is
  46. licensed under ``CC0``.
  47. The font used is **Titillium-Regular**, and is licensed under the ``SIL Open Font License, Version 1.1``.
  48. .. tip:: You can find the finished project for each part at the bottom of each part's page
  49. Part Overview
  50. -------------
  51. In this part we will be making a first person player that can move around
  52. the environment.
  53. .. image:: img/PartOneFinished.png
  54. By the end of this part you will have a working first person character who can move around the game environment,
  55. look around with a mouse based first person camera, that can jump into the air, turn on and off a flash light, and sprint.
  56. Getting everything ready
  57. ------------------------
  58. Launch Godot and open up the project included in the starter assets.
  59. .. note:: While these assets are not necessarily required to use the scripts provided in this tutorial,
  60. they will make the tutorial much easier to follow as there are several pre-setup scenes we
  61. will be using throughout the tutorial series.
  62. First, go open the project settings and go to the "Input Map" tab. You'll find several
  63. actions have already been defined. We will be using these actions for our player.
  64. Feel free to change the keys bound to these actions if you want.
  65. _________
  66. Let's take a second to see what we have in the starter assets.
  67. Included in the starter assets are several scenes. For example, in `res://` we have 14 scenes, most of which we will be visiting as
  68. we go through this tutorial series.
  69. For now let's open up ``Player.tscn``.
  70. .. note:: There are a bunch of scenes and a few textures in the ``Assets`` folder. You can look at these if you want,
  71. but we will not be exploring through ``Assets`` in this tutorial series. ``Assets`` contains all of the models used
  72. for each of the levels, as well as some textures and materials.
  73. Making the FPS movement logic
  74. -----------------------------
  75. Once you have ``Player.tscn`` open, let's take a quick look at how it is set up
  76. .. image:: img/PlayerSceneTree.png
  77. First, notice how the player's collision shapes are set up. Using a vertical pointing
  78. capsule as the collision shape for the player is fairly common in most first person games.
  79. We are adding a small square to the 'feet' of the player so the player does not
  80. feel like they are balancing on a single point.
  81. We do want the 'feet' slightly higher than the bottom of the capsule so we can roll over slight edges.
  82. Where to place the 'feet' is dependent on your levels and how you want your player to feel.
  83. .. note:: Many times player will notice how the collision shape being circular when
  84. they walk to an edge and slide off. We are adding the small square at the
  85. bottom of the capsule to reduce sliding on, and around, edges.
  86. Another thing to notice is how many nodes are children of ``Rotation_Helper``. This is because
  87. ``Rotation_Helper`` contains all of the nodes we want to rotate on the ``X`` axis (up and down).
  88. The reason behind this is so we can rotate ``Player`` on the ``Y`` axis, and ``Rotation_helper`` on
  89. the ``X`` axis.
  90. .. note:: If we did not use ``Rotation_helper`` then we'd likely have cases where we are rotating
  91. both the ``X`` and ``Y`` axes at the same time. This can lead to undesirable results, as we then
  92. could rotate on all three axes in some cases.
  93. See :ref:`using transforms <doc_using_transforms>` for more information
  94. _________
  95. Attach a new script to the ``Player`` node and call it ``Player.gd``.
  96. Let's program our player by adding the ability to move around, look around with the mouse, and jump.
  97. Add the following code to ``Player.gd``:
  98. ::
  99. extends KinematicBody
  100. const GRAVITY = -24.8
  101. var vel = Vector3()
  102. const MAX_SPEED = 20
  103. const JUMP_SPEED = 18
  104. const ACCEL= 4.5
  105. var dir = Vector3()
  106. const DEACCEL= 16
  107. const MAX_SLOPE_ANGLE = 40
  108. var camera
  109. var rotation_helper
  110. var MOUSE_SENSITIVITY = 0.05
  111. func _ready():
  112. camera = $Rotation_Helper/Camera
  113. rotation_helper = $Rotation_Helper
  114. Input.set_mouse_mode(Input.MOUSE_MODE_CAPTURED)
  115. func _physics_process(delta):
  116. process_input(delta)
  117. process_movement(delta)
  118. func process_input(delta):
  119. # ----------------------------------
  120. # Walking
  121. dir = Vector3()
  122. var cam_xform = camera.get_global_transform()
  123. var input_movement_vector = Vector2()
  124. if Input.is_action_pressed("movement_forward"):
  125. input_movement_vector.y += 1
  126. if Input.is_action_pressed("movement_backward"):
  127. input_movement_vector.y -= 1
  128. if Input.is_action_pressed("movement_left"):
  129. input_movement_vector.x -= 1
  130. if Input.is_action_pressed("movement_right"):
  131. input_movement_vector.x = 1
  132. input_movement_vector = input_movement_vector.normalized()
  133. dir += -cam_xform.basis.z.normalized() * input_movement_vector.y
  134. dir += cam_xform.basis.x.normalized() * input_movement_vector.x
  135. # ----------------------------------
  136. # ----------------------------------
  137. # Jumping
  138. if is_on_floor():
  139. if Input.is_action_just_pressed("movement_jump"):
  140. vel.y = JUMP_SPEED
  141. # ----------------------------------
  142. # ----------------------------------
  143. # Capturing/Freeing the cursor
  144. if Input.is_action_just_pressed("ui_cancel"):
  145. if Input.get_mouse_mode() == Input.MOUSE_MODE_VISIBLE:
  146. Input.set_mouse_mode(Input.MOUSE_MODE_CAPTURED)
  147. else:
  148. Input.set_mouse_mode(Input.MOUSE_MODE_VISIBLE)
  149. # ----------------------------------
  150. func process_movement(delta):
  151. dir.y = 0
  152. dir = dir.normalized()
  153. vel.y += delta*GRAVITY
  154. var hvel = vel
  155. hvel.y = 0
  156. var target = dir
  157. target *= MAX_SPEED
  158. var accel
  159. if dir.dot(hvel) > 0:
  160. accel = ACCEL
  161. else:
  162. accel = DEACCEL
  163. hvel = hvel.linear_interpolate(target, accel*delta)
  164. vel.x = hvel.x
  165. vel.z = hvel.z
  166. vel = move_and_slide(vel,Vector3(0,1,0), 0.05, 4, deg2rad(MAX_SLOPE_ANGLE))
  167. func _input(event):
  168. if event is InputEventMouseMotion and Input.get_mouse_mode() == Input.MOUSE_MODE_CAPTURED:
  169. rotation_helper.rotate_x(deg2rad(event.relative.y * MOUSE_SENSITIVITY))
  170. self.rotate_y(deg2rad(event.relative.x * MOUSE_SENSITIVITY * -1))
  171. var camera_rot = rotation_helper.rotation_degrees
  172. camera_rot.x = clamp(camera_rot.x, -70, 70)
  173. rotation_helper.rotation_degrees = camera_rot
  174. This is a lot of code, so let's break it down function by function:
  175. .. tip:: While copy and pasting code is ill advised, as you can learn a lot from manually typing the code in, you can
  176. copy and paste the code from this page directly into the script editor.
  177. If you do this, all of the code copied will be using spaces instead of tabs.
  178. To convert the spaces to tabs in the script editor, click the "edit" menu and select "Convert Indent To Tabs".
  179. This will convert all of the spaces into tabs. You can select "Convert Indent To Spaces" to convert t back into spaces.
  180. _________
  181. First, we define some global variables to dictate how our player will move about the world.
  182. .. note:: Throughout this tutorial, **variables defined outside functions will be
  183. referred to as "global variables"**. This is because we can access any of these
  184. variables from any place in the script. We can "globally" access them, hence the
  185. name.
  186. Let's go through each of the global variables:
  187. - ``GRAV``: How strong gravity pulls us down.
  188. - ``vel``: Our :ref:`KinematicBody <class_KinematicBody>`'s velocity.
  189. - ``MAX_SPEED``: The fastest speed we can reach. Once we hit this speed, we will not go any faster.
  190. - ``JUMP_SPEED``: How high we can jump.
  191. - ``ACCEL``: How fast we accelerate. The higher the value, the faster we get to max speed.
  192. - ``DEACCEL``: How fast we are going to decelerate. The higher the value, the faster we will come to a complete stop.
  193. - ``MAX_SLOPE_ANGLE``: The steepest angle our :ref:`KinematicBody <class_KinematicBody>` will consider as a 'floor'.
  194. - ``camera``: The :ref:`Camera <class_Camera>` node.
  195. - ``rotation_helper``: A :ref:`Spatial <class_Spatial>` node holding everything we want to rotate on the X axis (up and down).
  196. - ``MOUSE_SENSITIVITY``: How sensitive the mouse is. I find a value of ``0.05`` works well for my mouse, but you may need to change it based on how sensitive your mouse is.
  197. You can tweak many of these variables to get different results. For example, by lowering ``GRAVITY`` and/or
  198. increasing ``JUMP_SPEED`` you can get a more 'floaty' feeling character.
  199. Feel free to experiment!
  200. .. note:: You may have noticed that ``MOUSE_SENSITIVITY`` is written in all caps like the other constants, but is ``MOUSE_SENSITIVITY`` is not a constant.
  201. The reason behind this is we want to treat it like a constant variable (a variable that cannot change) throughout our script, but we want to be
  202. able to change the value later when we add customizable settings. So, in an effort to remind ourselves to treat it like a constant, it's named in all caps.
  203. _________
  204. Now let's look at the ``_ready`` function:
  205. First we get the ``camera`` and ``rotation_helper`` nodes and store them into their variables.
  206. Then we need to set the mouse mode to captured so the mouse cannot leave the game window.
  207. This will hide the mouse and keep it at the center of the screen. We do this for two reasons:
  208. The first reason being we do not want to the player to see their mouse cursor as they play.
  209. The second reason is because we do not want the cursor to leave the game window. If the cursor leaves
  210. the game window there could be instances where the player clicks outside the window, and then the game
  211. would lose focus. To assure neither of these issues happen, we capture the mouse cursor.
  212. .. note:: see :ref:`Input documentation <class_Input>` for the various mouse modes. We will only be using
  213. ``MOUSE_MODE_CAPTURED`` and ``MOUSE_MODE_VISIBLE`` in this tutorial series.
  214. _________
  215. Next let's take a look at ``_physics_process``:
  216. All we're doing in ``_physics_process`` is calling two functions: ``process_input`` and ``process_movement``.
  217. ``process_input`` will be where we store all of the code relating to player input. We want to call it first before
  218. anything else so we have fresh player input to work with.
  219. ``process_movement`` is where we'll send all of the date necessary to the :ref:`KinematicBody <class_KinematicBody>`
  220. so it can move through the game world.
  221. _________
  222. Let's look at ``process_input`` next:
  223. First we set ``dir`` to an empty :ref:`Vector3 <class_Vector3>`.
  224. ``dir`` will be used for storing the direction the player intends to move towards. Because we do not
  225. want the player's previous input to effect the player beyond a single ``process_movement`` call, we reset ``dir``.
  226. Next we get the camera's global transform and store it as well, into the ``cam_xform`` variable.
  227. The reason we need the camera's global transform is so we can use it's directional vectors.
  228. Many have found directional vectors confusing, so let's take a second to explain how they work:
  229. _________
  230. World space can be defined as: The space in which all objects are placed in, relative to a constant origin point.
  231. Every object, no matter if it is 2D or 3D, has a position in world space.
  232. To put it another way: world space is the space in a universe where every object's position, rotation, and scale
  233. can be measured by a known, fixed point called the origin.
  234. In Godot, the origin is at position ``(0, 0, 0)`` with a rotation of ``(0, 0, 0)`` and a scale of ``(1, 1, 1)``.
  235. .. note:: When you open up the Godot editor and select a :ref:`Spatial <class_Spatial>` based node, a gizmo pops up.
  236. Each of the arrows points using world space directions by default.
  237. If you want to move using the world space directional vectors, you'd do something like this:
  238. ::
  239. if Input.is_action_pressed("movement_forward"):
  240. node.translate(Vector3(0, 0, 1))
  241. if Input.is_action_pressed("movement_backward"):
  242. node.translate(Vector3(0, 0, -1))
  243. if Input.is_action_pressed("movement_left"):
  244. node.translate(Vector3(1, 0, 0))
  245. if Input.is_action_pressed("movement_right"):
  246. node.translate(Vector3(-1, 0, 0))
  247. .. note:: Notice how we do not need to do any calculations to get world space directional vectors.
  248. We can define a few :ref:`Vector3 <class_Vector3>` variables and input the values pointing in each direction.
  249. Here is what world space looks like in 2D:
  250. .. note:: The following images are just examples. Each arrow/rectangle represents a directional vector
  251. .. image:: img/WorldSpaceExample.png
  252. And here is what it looks like for 3D:
  253. .. image:: img/WorldSpaceExample_3D.png
  254. Notice how in both examples, the rotation of the node does not change the directional arrows.
  255. This is because world space is a constant. No matter how you translate, rotate, or scale an object, world
  256. space will *always point in the same direction*.
  257. Local space is different, because it takes the rotation of the object into account.
  258. Local space can be defined as follows:
  259. The space in which a object's position is the origin of the universe. Because the position
  260. of the origin can be at ``N`` many locations, the values derived from local space change
  261. with the position of the origin.
  262. .. note:: This stack overflow question has a much better explanation of world space and local space.
  263. https://gamedev.stackexchange.com/questions/65783/what-are-world-space-and-eye-space-in-game-development
  264. (Local space and eye space are essentially the same thing in this context)
  265. To get a :ref:`Spatial <class_Spatial>` node's local space, we need to get its :ref:`Transform <class_Transform>`, so then we
  266. can get the :ref:`Basis <class_Basis>` from the :ref:`Transform <class_Transform>`.
  267. Each :ref:`Basis <class_Basis>` has three vectors: ``X``, ``Y``, and ``Z``.
  268. Each of those vectors point towards each of the local space vectors coming from that object.
  269. To use the a :ref:`Spatial <class_Spatial>` node's local directional vectors, we use this code:
  270. ::
  271. if Input.is_action_pressed("movement_forward"):
  272. node.translate(node.global_transform.basis.z.normalized())
  273. if Input.is_action_pressed("movement_backward"):
  274. node.translate(-node.global_transform.basis.z.normalized())
  275. if Input.is_action_pressed("movement_left"):
  276. node.translate(node.global_transform.basis.x.normalized())
  277. if Input.is_action_pressed("movement_right"):
  278. node.translate(-node.global_transform.basis.x.normalized())
  279. Here is what local space looks like in 2D:
  280. .. image:: img/LocalSpaceExample.png
  281. And here is what it looks like for 3D:
  282. .. image:: img/LocalSpaceExample_3D.png
  283. Here is what the :ref:`Spatial <class_Spatial>` gizmo shows when you are using local space mode.
  284. Notice how the arrows follow the rotation of the object on the left, which looks exactly
  285. the same as the 3D example for local space.
  286. .. note:: You can change between local and world space modes by pressing the little cube button
  287. when you have a :ref:`Spatial <class_Spatial>` based node selected.
  288. .. image:: img/LocalSpaceExampleGizmo.png
  289. Local vectors are confusing even for more experienced game developers, so do not worry if this all doesn't make a
  290. lot of sense. The key thing to remember about local vectors is that we are using local coordinates to get direction
  291. from the object's point of view, as opposed to using world vectors which give direction from the world's point of view.
  292. _________
  293. Okay, back to ``process_input``:
  294. Next we make a new variable called ``input_movement_vector`` and assign it to an empty :ref:`Vector2 <class_Vector2>`.
  295. We will use this to make a virtual axis of sorts so map the player's input to movement.
  296. .. note:: This may seem overkill for just the keyboard, but this will make sense later when we add joypad input.
  297. Based on which directional movement action is pressed, we add or remove from ``input_movement_vector``.
  298. After we've checked each of the directional movement actions, we normalize ``input_movement_vector``. This makes it where ``input_movement_vector``'s values
  299. are within a ``1`` radius unit circle.
  300. Next we add the camera's local ``Z`` vector times ``input_movement_vector.y`` to ``dir``. This where when we pressed forward or backwards we add the camera's
  301. local ``Z`` axis, so we move forward in relation to the camera.
  302. .. note:: Because the camera is rotated by ``-180`` degrees, we have to flip the ``Z`` directional vector.
  303. Normally forward would be the positive Z axis, so using ``basis.z.normalized()`` would work,
  304. but we are using ``-basis.z.normalized()`` because our camera's Z axis faces backwards in relation
  305. to the rest of the player.
  306. We do the same thing for the camera's local ``X`` vector, and instead of using ``input_movement_vector.y`` we instead use ``input_movement_vector.x``.
  307. This makes it where when we press left or right, we move left/right in relation to the camera.
  308. Next we check if the player is on the floor using :ref:`KinematicBody <class_KinematicBody>`'s ``is_on_floor`` function. If it is, then we
  309. check to see if the "movement_jump" action has just been pressed. If it has, then we set our ``Y`` velocity to
  310. ``JUMP_SPEED``.
  311. Because we're setting the Y velocity, we will jump into the air.
  312. Then we check for the ``ui_cancel`` action. This is so we can free/capture the mouse cursor when the ``escape`` button
  313. is pressed. We do this because otherwise we'd have no way to free the cursor, meaning it would be stuck until you terminate the
  314. runtime.
  315. To free/capture the cursor, we check to see if the mouse is visible (freed) or not. If it is, then we capture it, and if it's not we make it visible (free it).
  316. That's all we're doing right now for ``process_input``. We'll come back several times to this function as we add more complexities to our player.
  317. _________
  318. Now let's look at ``process_movement``:
  319. First we assure that ``dir`` does not have any movement on the ``Y`` axis by setting it's ``Y`` value to zero.
  320. Next we normalize ``dir`` to assure we're within a ``1`` radius unit circle. This makes it where we're moving at a constant speed regardless
  321. of whether we've moving straight, or moving diagonal. If we did not normalize, we would move faster on the diagonal than when we're going straight.
  322. Next we add gravity to our player by adding ``GRAVITY * delta`` to our ``Y`` velocity.
  323. After that we assign our velocity to a new variable (called ``hvel``) and remove any movement on the ``Y`` axis.
  324. Next we set a new variable (``target``) to our direction vector.
  325. Then we multiply that by our max speed so we know how far we will can move in the direction provided by ``dir``.
  326. After that we make a new variable for our acceleration, named ``accel``.
  327. We then take the dot product of ``hvel`` to see if we are moving according to ``hvel``. Remember, ``hvel`` does not have any
  328. ``Y`` velocity, meaning we are only checking if we are moving forwards, backwards, left, or right.
  329. If we are moving according to ``hvel``, then we set ``accel`` to our ``ACCEL`` constant so we accelerate, otherwise we set ``accel`` to
  330. our ``DEACCEL`` constant so we decelerate.
  331. Then we interpolate our horizontal velocity, set our ``X`` and ``Z`` velocity to the interpolated horizontal velocity,
  332. and call ``move_and_slide`` to let the :ref:`KinematicBody <class_KinematicBody>` handle moving through the physics world.
  333. .. tip:: All of the code in ``process_movement`` is exactly the same as the movement code from the Kinematic Character demo!
  334. _________
  335. The final function we have is the ``_input`` function, and thankfully it's fairly short:
  336. First we make sure that the event we are dealing with is a :ref:`InputEventMouseMotion <class_InputEventMouseMotion>` event.
  337. We also want to check if the cursor is captured, as we do not want to rotate if it is not.
  338. .. note:: See :ref:`Mouse and input coordinates <doc_mouse_and_input_coordinates>` for a list of
  339. possible input events.
  340. If the event is indeed a mouse motion event and the cursor is captured, we rotate
  341. based on the relative mouse motion provided by :ref:`InputEventMouseMotion <class_InputEventMouseMotion>`.
  342. First we rotate the ``rotation_helper`` node on the ``X`` axis, using the relative mouse motion's
  343. ``Y`` value, provided by :ref:`InputEventMouseMotion <class_InputEventMouseMotion>`.
  344. Then we rotate the entire :ref:`KinematicBody <class_KinematicBody>` on the ``Y`` axis by the relative mouse motion's ``X`` value.
  345. .. tip:: Godot converts relative mouse motion into a :ref:`Vector2 <class_Vector2>` where mouse movement going
  346. up and down is ``1`` and ``-1`` respectively. Right and Left movement is
  347. ``1`` and ``-1`` respectively.
  348. Because of how we are rotating the player, we multiply the relative mouse motion's
  349. ``X`` value by ``-1`` so mouse motion going left and right rotates the player left and right
  350. in the same direction.
  351. Finally, we clamp the ``rotation_helper``'s ``X`` rotation to be between ``-70`` and ``70``
  352. degrees so we cannot rotate ourselves upside down.
  353. .. tip:: see :ref:`using transforms <doc_using_transforms>` for more information on rotating transforms.
  354. _________
  355. To test the code open up the scene named ``Testing_Area.tscn``, if it's not already opened up. We will be using
  356. this scene as we go through the tutorial, so be sure to keep it open in one of your scene tabs.
  357. Go ahead and test your code either by pressing ``F4`` with ``Testing_Area.tscn`` as the open tab, by pressing the
  358. play button in the top right corner, or by pressing ``F6``.
  359. You should now be able to walk around, jump in the air, and look around using the mouse.
  360. Giving the player a flash light and the option to sprint
  361. --------------------------------------------------------
  362. Before we get to making the weapons work, there is a couple more things we should add.
  363. Many FPS games have an option to sprint and a flash light. We can easily add these to our player,
  364. so let's do that!
  365. First we need a few more global variables in our player script:
  366. ::
  367. const MAX_SPRINT_SPEED = 30
  368. const SPRINT_ACCEL = 18
  369. var is_sprinting = false
  370. var flashlight
  371. All of the sprinting variables work exactly the same as the non sprinting variables with
  372. similar names.
  373. ``is_sprinting`` is a boolean to track whether the player is currently sprinting, and ``flashlight`` is a variable
  374. we will be using to hold our flash light node.
  375. Now we need to add a few lines of code, starting in ``_ready``. Add the following to ``_ready``:
  376. ::
  377. flashlight = $Rotation_Helper/Flashlight
  378. This gets our flash light node and assigns it to the ``flashlight`` variable.
  379. _________
  380. Now we need to change some of the code in ``process_input``. Add the following somewhere in ``process_input``:
  381. ::
  382. # ----------------------------------
  383. # Sprinting
  384. if Input.is_action_pressed("movement_sprint"):
  385. is_sprinting = true
  386. else:
  387. is_sprinting = false
  388. # ----------------------------------
  389. # ----------------------------------
  390. # Turning the flashlight on/off
  391. if Input.is_action_just_pressed("flashlight"):
  392. if flashlight.is_visible_in_tree():
  393. flashlight.hide()
  394. else:
  395. flashlight.show()
  396. # ----------------------------------
  397. Let's go over the additions:
  398. We set ``is_sprinting`` to true when we are holding down the ``movement_sprint`` action, and false
  399. when the ``movement_sprint`` action is released. In ``process_movement`` we'll add the code that makes the player faster when
  400. they sprint. Here in ``process_input`` we're going to change the ``is_sprinting`` variable.
  401. We do something similar freeing/capturing the cursor for handling the flash light. We first check to see if the ``flashlight`` action
  402. was just pressed. If it was, we then check to see if ``flashlight`` is visible in the scene tree. If it is, then we hide it, and if it's not we show it.
  403. _________
  404. Now we need to change a couple things in ``process_movement``. First, replace ``target *= MAX_SPEED`` with the following:
  405. ::
  406. if is_sprinting:
  407. target *= MAX_SPRINT_SPEED
  408. else:
  409. target *= MAX_SPEED
  410. Now instead of always multiplying ``target`` by ``MAX_SPEED``, we first check to see if we are sprinting or not.
  411. If we are sprinting, we instead multiply ``target`` by ``MAX_SPRINT_SPEED``.
  412. Now all that's left is changing the accleration when sprinting. Change ``accel = ACCEL`` to the following:
  413. ::
  414. if is_sprinting:
  415. accel = SPRINT_ACCEL
  416. else:
  417. accel = ACCEL
  418. Now when we are sprinting we'll use ``SPRINT_ACCEL`` instead of ``ACCEL``, which will accelerate us faster.
  419. _________
  420. You should now be able to sprint if you press the ``shift`` button, and can toggle the flash light on and off by pressing the ``F`` button!
  421. Go give it a whirl! You can change the sprint related global variables to make the player faster or slower when sprinting!
  422. Final notes
  423. -----------
  424. .. image:: img/PartOneFinished.png
  425. Phew! That was a lot of work. Now you have a fully working first person character!
  426. In :ref:`doc_fps_tutorial_part_two` we will add some guns to our player character.
  427. .. note:: At this point we've recreated the Kinematic character demo from first person perspective with sprinting and a flash light!
  428. .. tip:: Currently the player script would be at an ideal state for making all sorts of
  429. first person games. For example: Horror games, platformer games, adventure games, and more!
  430. .. warning:: If you ever get lost, be sure to read over the code again!
  431. You can download the finished project for this part here: :download:`Godot_FPS_Part_1.zip <files/Godot_FPS_Part_1.zip>`