vr_starter_tutorial.rst 68 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437
  1. .. _doc_vr_starter_tutorial:
  2. VR Starter Tutorial
  3. ===================
  4. Tutorial introduction
  5. ---------------------
  6. .. image:: img/starter_vr_tutorial_sword.png
  7. This tutorial series will show you how to make a simple VR game/project. The intent of this tutorial is to give you an idea
  8. on how to make VR games in Godot.
  9. Keep in mind, **one of the most important things when making VR content is getting the scale of your assets correct**!
  10. It can take lots of practice and iterations to get this right, but there are a few things you can do to make it easier:
  11. - In VR, 1 unit is often considered 1 meter. If you design your assets around that standard, you can save yourself a lot of headache.
  12. - In your 3D model program, see if there is a way to measure and use real world distances. In Blender you can use the MeasureIt add-on, in Maya you can use the Measure Tool.
  13. - You can make rough models using a tool like Google Blocks, and then refine in another 3D modelling program.
  14. - Test often, as the assets can look dramatically different in VR then on a flat screen!
  15. Throughout the course of this tutorial, we will cover:
  16. - How to tell Godot to run in VR.
  17. - How to make a teleportation system for moving the player.
  18. - How to make a directional movement system (locomotion) for moving the player.
  19. - How to make a :ref:`RigidBody <class_RigidBody>` based pick up and drop system.
  20. - How to make various items that can be used in VR
  21. .. note:: While this tutorial can be completed by beginners, it is highly
  22. advised to complete :ref:`doc_your_first_game`,
  23. if you are new to Godot and/or game development and have some experience with making 3D games
  24. **before** going through this tutorial series.
  25. This tutorial assumes you know have experience working with the Godot editor,
  26. have basic programming experience in GDScript, and have basic 3D game development experience.
  27. Also, it is assumed you have both a OpenVR ready headset and two OpenVR ready controllers! This tutorial was written using a Windows Mixed Reality headset on Windows 10,
  28. so the tutorial is written to work on that. You may need to adjust and/or the code to work with other VR headsets like the Oculus Rift, or the HTC Vive.
  29. You can find the start assets for this tutorial here: :download:`VR_Starter_Tutorial_Start.zip <files/VR_Starter_Tutorial_Start.zip>`
  30. The provided starter assets contain some 3D models, Sounds, and a few scenes already set up and configured for this tutorial.
  31. 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:
  32. .. note:: The skybox is created by **CGTuts** and is a ocean HDRI freebie, which you can find here: https://cgi.tutsplus.com/articles/freebie-8-awesome-ocean-hdris--cg-5684
  33. The font used is **Titillium-Regular**, and is licensed under the ``SIL Open Font License, Version 1.1``.
  34. The audio used are from several different sources, all **downloaded from the Sonnis #GameAudioGDC Bundle**. The license for the sound effects is included as a PDF,
  35. and you can find at this link: (https://sonniss.com/gdc-bundle-license/).
  36. The folders where the audio files are stored have the same name as folders in the bundle.
  37. The **OpenVR addon** is created by Bastiaan Olij, and is released under the MIT license, and can be found both on the Godot Asset Library, and here on
  38. Github: https://github.com/GodotVR/godot-openvr-asset
  39. Everything else is original and created solely for this tutorial by TwistedTwigleg. They are released under the MIT license, so feel free to use however you see fit!
  40. .. tip:: You can find the finished project at the bottom of this page
  41. Getting everything ready
  42. ------------------------
  43. Launch Godot and open up the project included in the starter assets.
  44. .. note:: While these assets are not necessarily required to use the scripts provided in this tutorial,
  45. they will make the tutorial much easier to follow as there are several pre-setup scenes we
  46. will be using throughout the tutorial series.
  47. First, you may notice there is already quite a bit set up. This includes A pre-built level, several instanced scenes placed around,
  48. some background music, and several GUI related :ref:`MeshInstances <class_MeshInstance>` nodes.
  49. You may notice that the GUI related meshes already have a script attached to them, and this is simply used to show whatever is inside the :ref:`Viewport <class_Viewport>`
  50. on the mesh. Feel free to take a look if you want, but this tutorial will not be going over how to use the :ref:`Viewport <class_Viewport>` nodes for making 3D GUI
  51. :ref:`MeshInstance <class_MeshInstance>` nodes.
  52. The other thing to notice before we jump in to writing the code is how the :ref:`ARVROrigin <class_ARVROrigin>` node works. How it works is kind of hard to explain,
  53. especially if you have never used VR before, but here is the gist of it:
  54. The :ref:`ARVROrigin <class_ARVROrigin>` node is the center point of the room. If there is no room scale tracking, then the :ref:`ARVROrigin <class_ARVROrigin>` will
  55. be directly below the player, but if there is room scale tracking, then the :ref:`ARVROrigin <class_ARVROrigin>` will be the center of the tracked room.
  56. .. note:: This is a bit of a simplification, and honestly, I do not know enough about the various different VR headsets and how they work to give a more detailed
  57. and complete explanation. The simple way is to look at it like this: The :ref:`ARVROrigin <class_ARVROrigin>` is the center of the VR world. If there is
  58. room tracking, the player can move away from the center point, the :ref:`ARVROrigin <class_ARVROrigin>` node, but only as far as the room scaling tracks.
  59. If you select the :ref:`ARVROrigin <class_ARVROrigin>` node, you may notice that the world scale is set to ``1.4``. This is because I originally made the world too big,
  60. and so I needed to scale the VR player slightly so they better fit the world. As mentioned earlier, keeping the scale relatively constant is very important!
  61. Another thing to notice here is how we have everything set up under the :ref:`ARVROrigin <class_ARVROrigin>` node. The player camera is a :ref:`ARVRCamera <class_ARVRCamera>`
  62. that represents the player's head in the game. The :ref:`ARVRCamera <class_ARVRCamera>` will be offset by the player's height, and if there is room tracking, then the camera
  63. can move around 3D space as well, relative to the :ref:`ARVROrigin <class_ARVROrigin>`. This is important to note, especially for later when we add teleporting.
  64. Notice how there is a :ref:`ColorRect <class_ColorRect>` node called ``Movement_Vignette``. This will be a vignette shader that will only be visible when the player is moving.
  65. We are going to use the vignette shader to help reduce motion sickness while moving in VR.
  66. The reason it is a child of :ref:`ARVROrigin <class_ARVROrigin>` is because we want it to easily access the VR controllers.
  67. The final thing to note is that there are two :ref:`ARVRController <class_ARVRController>` nodes, and these will represent the left and right controllers in 3D space.
  68. A :ref:`ARVRController <class_ARVRController>` with an ID of ``1`` is the left hand, while a :ref:`ARVRController <class_ARVRController>` with an ID of ``2`` is the right hand.
  69. Starting VR
  70. -----------
  71. First, let's get the VR up and going! While ``Game.tscn`` is open, select the ``Game`` node and make a new script called ``Game.gd``. Add the following code:
  72. ::
  73. extends Spatial
  74. func _ready():
  75. var VR = ARVRServer.find_interface("OpenVR")
  76. if VR and VR.initialize():
  77. get_viewport().arvr = true
  78. get_viewport().hdr = false
  79. OS.vsync_enabled = false
  80. Engine.target_fps = 90
  81. # Also, the physics FPS in the project settings is also 90 FPS. This makes the physics
  82. # run at the same frame rate as the display, which makes things look smoother in VR!
  83. Now, for this to work you will need to have the OpenVR asset from the Godot asset library. The OpenVR asset is included in the starter assets, but there may be newer
  84. versions that work better, so I would highly suggest deleting the ``addons`` folder, going to the asset library, searching for ``OpenVR``, and downloading the newest
  85. version from Bastiaan-Olij/Mux213!
  86. With that done, let's quickly go over what this script does.
  87. First, we find a VR interface from the ARVR server. We do this because by default Godot does not include any VR interfaces, but rather exposes a API so anyone can make
  88. AR/VR interfaces with GDNative/C++. Next, we check to see if a OpenVR interface was found, and then we initialize it.
  89. Assuming nothing went wrong with initializing, we then turn the main :ref:`Viewport <class_Viewport>` into a AR/VR viewport, by setting ``arvr`` to ``true``.
  90. We also set HDR to ``false``, since in OpenVR you cannot use HDR.
  91. Then we disable VSync and set the target FPS to ``90`` frames per second. ``90`` FPS is what most VR headsets run at, and since the game will both display
  92. on the VR headset and on the computer's monitor, we want to disable VSync and set the target FPS manually so the computer's monitor does not drag the VR display down to 60 FPS.
  93. .. note:: One thing to notice as well is that the physics FPS is also set to ``90``! This makes the physics run at the same frame rate as the display, which makes
  94. things look smoother in VR.
  95. .. image:: img/starter_vr_tutorial_hands.png
  96. With that done, go ahead and give the game a try! If everything goes well, you will now be able to look around the world! If you have a VR headset with room tracking,
  97. you will be able to move around as far as the room tracking allows.
  98. Coding the controllers
  99. ----------------------
  100. While perhaps interesting if we were making a VR film, we really want to do more than stand around and look. Currently we cannot move outside of the room tracking boundaries
  101. (assuming your VR headset has room tracking) and we cannot interact with anything! Let's change that!
  102. You may have noticed that you have a pair of green and black hands following the controllers. Now let's write the code for those controllers, which will allow the player to teleport
  103. around the world and allow the player to grab and release :ref:`RigidBody <class_RigidBody>` nodes.
  104. Open either ``Left_Controller.tscn`` or ``Right_Controller.tscn``.
  105. Feel free to look at how the scene is set up. There is only a couple things of note to point out.
  106. First, notice how there is a couple :ref:`Raycast <class_Raycast>` nodes. We will be using one :ref:`Raycast <class_Raycast>` to teleport around the game world (``Raycast``) and
  107. we will use the other for picking up objects (``GrabCast``) if the player is using :ref:`Raycast <class_Raycast>` nodes to pick up objects.
  108. The other thing to note is how there is an :ref:`Area <class_Area>`, simply called ``Area``, that is a small sphere in the palm of the hand. This will be used to detect
  109. objects the player can pick up with that hand if the player is using :ref:`Area <class_Area>` nodes to pick up objects.
  110. We also have a larger :ref:`Area <class_Area>` called ``Sleep_Area``, which will simply be used to wake :ref:`RigidBody <class_RigidBody>` nodes when the hands get close.
  111. Select the root node, either ``Left_Controller`` or ``Right_Controller`` depending on which scene you chose, and create a new script called ``VR_Controller.gd``.
  112. Add the following to ``VR_Controller.gd``:
  113. ::
  114. extends ARVRController
  115. var controller_velocity = Vector3(0,0,0)
  116. var prior_controller_position = Vector3(0,0,0)
  117. var prior_controller_velocities = []
  118. var held_object = null
  119. var held_object_data = {"mode":RigidBody.MODE_RIGID, "layer":1, "mask":1}
  120. var grab_area
  121. var grab_raycast
  122. var grab_mode = "AREA"
  123. var grab_pos_node
  124. var hand_mesh
  125. var teleport_pos
  126. var teleport_mesh
  127. var teleport_button_down
  128. var teleport_raycast
  129. const CONTROLLER_DEADZONE = 0.65
  130. const MOVEMENT_SPEED = 1.5
  131. var directional_movement = false
  132. func _ready():
  133. teleport_raycast = get_node("RayCast")
  134. teleport_mesh = get_tree().root.get_node("Game/Teleport_Mesh")
  135. teleport_button_down = false
  136. grab_area = get_node("Area")
  137. grab_raycast = get_node("GrabCast")
  138. grab_pos_node = get_node("Grab_Pos")
  139. grab_mode = "AREA"
  140. get_node("Sleep_Area").connect("body_entered", self, "sleep_area_entered")
  141. get_node("Sleep_Area").connect("body_exited", self, "sleep_area_exited")
  142. hand_mesh = get_node("Hand")
  143. connect("button_pressed", self, "button_pressed")
  144. connect("button_release", self, "button_released")
  145. func _physics_process(delta):
  146. if teleport_button_down == true:
  147. teleport_raycast.force_raycast_update()
  148. if teleport_raycast.is_colliding():
  149. if teleport_raycast.get_collider() is StaticBody:
  150. if teleport_raycast.get_collision_normal().y >= 0.85:
  151. teleport_pos = teleport_raycast.get_collision_point()
  152. teleport_mesh.global_transform.origin = teleport_pos
  153. # Controller velocity
  154. # --------------------
  155. if get_is_active() == true:
  156. controller_velocity = Vector3(0,0,0)
  157. if prior_controller_velocities.size() > 0:
  158. for vel in prior_controller_velocities:
  159. controller_velocity += vel
  160. # Get the average velocity, instead of just adding them together.
  161. controller_velocity = controller_velocity / prior_controller_velocities.size()
  162. prior_controller_velocities.append((global_transform.origin - prior_controller_position) / delta)
  163. controller_velocity += (global_transform.origin - prior_controller_position) / delta
  164. prior_controller_position = global_transform.origin
  165. if prior_controller_velocities.size() > 30:
  166. prior_controller_velocities.remove(0)
  167. # --------------------
  168. if held_object != null:
  169. var held_scale = held_object.scale
  170. held_object.global_transform = grab_pos_node.global_transform
  171. held_object.scale = held_scale
  172. # Directional movement
  173. # --------------------
  174. # NOTE: you may need to change this depending on which VR controllers
  175. # you are using and which OS you are on.
  176. var trackpad_vector = Vector2(-get_joystick_axis(1), get_joystick_axis(0))
  177. var joystick_vector = Vector2(-get_joystick_axis(5), get_joystick_axis(4))
  178. if trackpad_vector.length() < CONTROLLER_DEADZONE:
  179. trackpad_vector = Vector2(0,0)
  180. else:
  181. trackpad_vector = trackpad_vector.normalized() * ((trackpad_vector.length() - CONTROLLER_DEADZONE) / (1 - CONTROLLER_DEADZONE))
  182. if joystick_vector.length() < CONTROLLER_DEADZONE:
  183. joystick_vector = Vector2(0,0)
  184. else:
  185. joystick_vector = joystick_vector.normalized() * ((joystick_vector.length() - CONTROLLER_DEADZONE) / (1 - CONTROLLER_DEADZONE))
  186. var forward_direction = get_parent().get_node("Player_Camera").global_transform.basis.z.normalized()
  187. var right_direction = get_parent().get_node("Player_Camera").global_transform.basis.x.normalized()
  188. var movement_vector = (trackpad_vector + joystick_vector).normalized()
  189. var movement_forward = forward_direction * movement_vector.x * delta * MOVEMENT_SPEED
  190. var movement_right = right_direction * movement_vector.y * delta * MOVEMENT_SPEED
  191. movement_forward.y = 0
  192. movement_right.y = 0
  193. if (movement_right.length() > 0 or movement_forward.length() > 0):
  194. get_parent().translate(movement_right + movement_forward)
  195. directional_movement = true
  196. else:
  197. directional_movement = false
  198. # --------------------
  199. func button_pressed(button_index):
  200. # If the trigger is pressed...
  201. if button_index == 15:
  202. if held_object != null:
  203. if held_object.has_method("interact"):
  204. held_object.interact()
  205. else:
  206. if teleport_mesh.visible == false and held_object == null:
  207. teleport_button_down = true
  208. teleport_mesh.visible = true
  209. teleport_raycast.visible = true
  210. # If the grab button is pressed...
  211. if button_index == 2:
  212. if (teleport_button_down == true):
  213. return
  214. if held_object == null:
  215. var rigid_body = null
  216. if (grab_mode == "AREA"):
  217. var bodies = grab_area.get_overlapping_bodies()
  218. if len(bodies) > 0:
  219. for body in bodies:
  220. if body is RigidBody:
  221. if !("NO_PICKUP" in body):
  222. rigid_body = body
  223. break
  224. elif (grab_mode == "RAYCAST"):
  225. grab_raycast.force_raycast_update()
  226. if (grab_raycast.is_colliding()):
  227. if grab_raycast.get_collider() is RigidBody and !("NO_PICKUP" in grab_raycast.get_collider()):
  228. rigid_body = grab_raycast.get_collider()
  229. if rigid_body != null:
  230. held_object = rigid_body
  231. held_object_data["mode"] = held_object.mode
  232. held_object_data["layer"] = held_object.collision_layer
  233. held_object_data["mask"] = held_object.collision_mask
  234. held_object.mode = RigidBody.MODE_STATIC
  235. held_object.collision_layer = 0
  236. held_object.collision_mask = 0
  237. hand_mesh.visible = false
  238. grab_raycast.visible = false
  239. if (held_object.has_method("picked_up")):
  240. held_object.picked_up()
  241. if ("controller" in held_object):
  242. held_object.controller = self
  243. else:
  244. held_object.mode = held_object_data["mode"]
  245. held_object.collision_layer = held_object_data["layer"]
  246. held_object.collision_mask = held_object_data["mask"]
  247. held_object.apply_impulse(Vector3(0, 0, 0), controller_velocity)
  248. if held_object.has_method("dropped"):
  249. held_object.dropped()
  250. if "controller" in held_object:
  251. held_object.controller = null
  252. held_object = null
  253. hand_mesh.visible = true
  254. if (grab_mode == "RAYCAST"):
  255. grab_raycast.visible = true
  256. get_node("AudioStreamPlayer3D").play(0)
  257. # If the menu button is pressed...
  258. if grab_mode == "AREA":
  259. grab_mode = "RAYCAST"
  260. if held_object == null:
  261. grab_raycast.visible = true
  262. elif grab_mode == "RAYCAST":
  263. grab_mode = "AREA"
  264. grab_raycast.visible = false
  265. func button_released(button_index):
  266. # If the trigger button is released...
  267. if button_index == 15:
  268. if (teleport_button_down == true):
  269. if teleport_pos != null and teleport_mesh.visible == true:
  270. var camera_offset = get_parent().get_node("Player_Camera").global_transform.origin - get_parent().global_transform.origin
  271. camera_offset.y = 0
  272. get_parent().global_transform.origin = teleport_pos - camera_offset
  273. teleport_button_down = false
  274. teleport_mesh.visible = false
  275. teleport_raycast.visible = false
  276. teleport_pos = null
  277. func sleep_area_entered(body):
  278. if "can_sleep" in body:
  279. body.can_sleep = false
  280. body.sleeping = false
  281. func sleep_area_exited(body):
  282. if "can_sleep" in body:
  283. body.can_sleep = true
  284. This is quite a bit of code (``245`` lines to be exact) of code to go through, so let's break it down bit by bit. First, let's start with the class variables, which are
  285. variables outside of any/all functions.
  286. - ``controller_velocity`` : The velocity the controller is moving at. We will calculate this by changes in position every physics frame.
  287. - ``prior_controller_position`` : The controller's previous position. We will use this to calculate the controller's velocity.
  288. - ``prior_controller_velocities`` : The last ``30`` calculated velocities (1/3 of a second worth of velocities, assuming the game is running at ``90`` FPS)
  289. - ``held_object`` : The currently held object, a :ref:`RigidBody <class_RigidBody>`, if there is one.
  290. - ``held_object_data`` : The data of the currently held object, used to reset the object when it is no longer being held.
  291. - ``grab_area`` : The :ref:`Area <class_Area>` node used to grab objects.
  292. - ``grab_pos_node`` : The position where held objects stay.
  293. - ``hand_mesh`` : The hand mesh, used to represent the player's hand when they are not holding anything.
  294. - ``teleport_pos`` : The position the teleport :ref:`Raycast <class_Raycast>` is aimed at.
  295. - ``teleport_mesh`` : The meshed used to represent the teleport position.
  296. - ``teleport_button_down`` : A variable for tracking whether the teleport button is being held down or not.
  297. - ``teleport_raycast`` : The teleport :ref:`Raycast <class_Raycast>` node, used for calculating the teleportation position.
  298. - ``CONTROLLER_DEADZONE`` : The dead zone for both the trackpad and the joystick.
  299. - ``MOVEMENT_SPEED`` : The speed the player moves at when moving using the trackpad and/or the joystick.
  300. - ``directional_movement`` : A boolean to track whether the player is moving using this controller.
  301. _________
  302. Next, let's go through ``_ready``.
  303. First we get the teleport :ref:`Raycast <class_Raycast>` node and assign it to ``teleport_raycast``.
  304. Next we get the teleport mesh, and notice how we are getting it from ``Game/Teleport_Mesh`` using ``get_tree().root``. This is because we need the teleport mesh
  305. to be separate from the controller, so moving and rotating the controller does not effect the position and rotation of the teleporation mesh.
  306. Then we get the grab area, grab :ref:`Raycast <class_Raycast>`, and position node and assign them to the proper variables.
  307. We set the default grab mode to ``AREA`` so it uses the :ref:`Area <class_Area>` node to grab objects by default.
  308. Then we connect the ``body_entered`` and ``body_exited`` signals from the sleep area node, we get the hand mesh and assign it the proper variable, and finally
  309. we connect the ``button_pressed`` and ``button_released`` signals from the :ref:`ARVRController <class_ARVRController>`.
  310. _________
  311. Now let's go through ``_physics_process``.
  312. First we check to see if the teleportation button is down or not. If the teleportation button is down, we then force the teleportation :ref:`Raycast <class_Raycast>`
  313. to update, which will give us frame perfect collision detection. We then check to see if the :ref:`Raycast <class_Raycast>` is colliding with anything.
  314. Next, we check to see if the collision body the :ref:`Raycast <class_Raycast>` is colliding with is a :ref:`StaticBody <class_StaticBody>`. We do this to ensures the player
  315. can only teleport on :ref:`StaticBody <class_StaticBody>` nodes. We then check to see if the ``Y`` value returned by the :ref:`Raycast <class_Raycast>`'s
  316. ``get_collision_normal`` function is more than ``0.85``, which is mostly pointing straight up. This allows the player only to teleport on fairly flat faces pointing upwards.
  317. If all those checks for the teleport :ref:`Raycast <class_Raycast>` return true, we then set ``teleport_pos`` to the collision point, and we move the teleportation
  318. mesh to ``teleport_pos``.
  319. The next thing we check is to see if the :ref:`ARVRController <class_ARVRController>` is active or not. If the :ref:`ARVRController <class_ARVRController>` is active, then
  320. that means there is a controller and it is being tracked. If the controller is active, we then reset ``controller_velocity`` to a empty :ref:`Vector3 <class_Vector3>`.
  321. We then add all of the prior velocity calculations in ``prior_controller_velocities`` to ``controller_velocity``. By using the prior calculations, we get a smoother
  322. throwing/catching experience, though it is not perfect. We want to get the average of these velocities, as otherwise we'd get crazy high velocity numbers that are not realistic.
  323. Next we calculate the velocity from the position the controller currently is, from the position the controller was at. We can use this difference in position to help track
  324. the controller's velocity.
  325. We then add the velocity from the controller this physics frame and the last physics frame to ``controller_velocity``. We then update ``prior_controller_position`` to the
  326. current position, so we can use it in the calculations in the velocity next physics frame.
  327. .. note:: The way we are calculating velocity is not perfect by any means, since it relies on a consistent amount of frames per second.
  328. Ideally we would be able to find the velocity directly from the VR controller but currently in OpenVR there is not way to access the controller's velocity.
  329. We can get pretty close to the real velocity by comparing positions between frames though, and this will work just fine for this project.
  330. Then we check to see if we have more than ``30`` stored velocities (more than a third of a second). If there are more than ``30``, we remove the oldest velocity
  331. from ``prior_controller_velocities``.
  332. Next we check to see if there is a held object. If there is, we update the position and rotation of the held object to the
  333. position and rotation of ``grab_pos_node``. Because of how scale works, we need to temporarily store the scale and then reset the scale once we have updated the transform, as
  334. otherwise the scale will always be the same as the controller, which will break the immersion if the player grabs a scaled object.
  335. The last thing we are going to do in ``_physics_process`` is move the player if they are moving the trackpad/joystick on the VR controller.
  336. First, we convert the axis values into :ref:`Vector2 <class_Vector2>` variables so we can process them. We invert the X axis so moving the trackpad/joystick left
  337. will move the player left.
  338. .. note:: Depending on your VR controller and OS, you may need to change the code so it gets the proper axis values!
  339. Next we account for dead zones on both the trackpad and the joystick. The code for doing this is adapted from the link below, and I would highly recommend looking at it.
  340. .. tip:: You can find a great article explaining joystick deads zone here: http://www.third-helix.com/2013/04/12/doing-thumbstick-dead-zones-right.html
  341. One thing to note is how large we are making the dead zones. The reason we are using such large dead zones is to the player cannot move themselves accidentaly by placing their
  342. finger on the center of the touchpad/joystick, which make players feel motion sick if they are not expecting it.
  343. Next, we get the forward and right directional vectors from the VR camera. We need these so we can move the player forward/backwards and right/left based on where
  344. they are currently looking.
  345. Then we calculate how much the player will be moving by adding both the trackpad and the joystick vectors together and normalizing them.
  346. Next we calculate how far the player will go forwards/backwards and right/left by multiplying the VR camera's directional vectors by the combined trackpad/joystick vector.
  347. We then remove movement on the Y axis so the player cannot fly/fall simply by moving using the trackpad/joystick.
  348. And finally, we move the player if there is any movement forwards/backwards or right/left. If we are moving the player, we set ``directional_movement`` accordingly.
  349. _________
  350. Now, let's look at ``button_pressed``.
  351. If the button pressed is button ``15``, which for the Windows Mixed Reality controllers is the trigger button, we will interact with the held object assuming the
  352. controller is holding one, and if the player is not holding a object, we will try to start teleporting.
  353. If the controller is holding a object, and the held object has a method/function called ``interact``, we call the ``interact`` function
  354. on the held object.
  355. If the controller is not holding a object, we then check to make sure the teleportation mesh is not visible. This check ensure the player cannot teleport cannot teleport with
  356. both hands/controllers at the same time. If the teleportation mesh is not visible, we set ``teleport_button_down`` to ``true``, make ``teleport_mesh`` visible,
  357. and make the teleportation raycast visible. This makes it where the teleportation mesh will follow the :ref:`Raycast <class_Raycast>` coming from the pointer
  358. finger of the hand.
  359. If the button pressed is button ``2``, which for the Windows Mixed Reality controllers is the grab/grip button, we will grab/throw a object.
  360. First, we make sure the player is not trying to teleport, as we do not want the player to be able to grab something while in the middle of trying to teleport.
  361. Then we check to see if the controller is already holding a object or not.
  362. If the controller is not holding a object, we check to see which grab mode the player is using.
  363. If the player is using the ``AREA`` grab mode, we then get all of the bodies overlapping the grab :ref:`Area <class_Area>`. We go through all of the bodies in the
  364. grab :ref:`Area <class_Area>` and see if there is a :ref:`RigidBody <class_RigidBody>`. We also check to make sure any :ref:`RigidBody <class_RigidBody>` nodes in
  365. the :ref:`Area <class_Area>` do not have a variable called ``NO_PICKUP``, since we do not want to be able to pick up nodes with that variable.
  366. Assuming there is a :ref:`RigidBody <class_RigidBody>` node inside the grab :ref:`Area <class_Area>` that does not have a variable called ``NO_PICKUP``,
  367. we assign it to ``rigid_body`` for additional processing.
  368. If the player is using the ``RAYCAST`` grab mode, we first force the :ref:`Raycast <class_Raycast>` to update. We then check to see if the :ref:`Raycast <class_Raycast>`
  369. is colliding with something.
  370. If the :ref:`Raycast <class_Raycast>` is colliding with something, we then check to see if what is colliding with is a :ref:`RigidBody <class_RigidBody>`, and that it does not have
  371. a variable called ``NO_PICKUP``. If the :ref:`Raycast <class_Raycast>` is colliding with a :ref:`RigidBody <class_RigidBody>`, and it does not have a
  372. variable called ``NO_PICKUP``, we assign it to ``rigid_body`` for additional processing.
  373. If ``rigid_body`` is not ``null``, meaning we found a :ref:`RigidBody <class_RigidBody>` in the grab :ref:`Area <class_Area>`, we assign ``held_object`` to it.
  374. Then we store the now held :ref:`RigidBody <class_RigidBody>`'s information in ``held_object_data``. We are storing the :ref:`RigidBody <class_RigidBody>` mode, layer,
  375. and mask so later when we drop it, we can reset all of those variables back to what they were before we picked up the :ref:`RigidBody <class_RigidBody>`.
  376. We then set the held object's :ref:`RigidBody <class_RigidBody>` mode to ``MODE_STATIC`` and set the collision layer and mask to ``0`` so it cannot collide with any
  377. other physic bodies.
  378. We make the hand mesh invisible so it does not get in the way of the object we are holding (and also because I did not feel like animating the hand :P ). We also make the
  379. grab :ref:`Raycast <class_Raycast>` invisible so the mesh used for showing the :ref:`Raycast <class_Raycast>` is no longer visible.
  380. If the :ref:`RigidBody <class_RigidBody>` we picked up has the ``picked_up`` method/function, we call it. If the :ref:`RigidBody <class_RigidBody>` we picked up has a
  381. variable called ``controller``, we set it to this controller.
  382. If the controller is not holding a object, and the button pressed is ``2``, we want to drop/throw the held object.
  383. First, we set the held :ref:`RigidBody <class_RigidBody>`'s mode, layer, and mask back to what they were when we picked the object up.
  384. We then apply a impulse to the held object, using the controller's velocity as the force.
  385. If the previously held :ref:`RigidBody <class_RigidBody>` has a function called ``dropped``, we call it. If the :ref:`RigidBody <class_RigidBody>` has a variable
  386. called ``controller`` we set it to ``null``.
  387. Then we set ``held_object`` to ``null``, since we are no longer holding any objects, and we make the hand mesh visible again.
  388. If we are using the ``RAYCAST`` grab mode, we make the :ref:`Raycast <class_Raycast>` visible so we can see the mesh used for showing the grab :ref:`Raycast <class_Raycast>`.
  389. Finally, regardless of whether we are grabbing a object or releasing it, we play the sound loaded into ``AudioStreamPlayer3D``, which is a pick-up/drop noise.
  390. The last thing we are doing in ``button_pressed`` is checking to see if the button pressed is ``1``, which for the Windows Mixed Reality controllers is the menu button.
  391. If the menu button is pressed, we change grab modes, and set the visibility of the grab :ref:`Raycast <class_Raycast>` so it is only visible when using ``RAYCAST`` as the grab mode.
  392. _________
  393. Let's look at ``button_released`` next.
  394. If the button released is button ``15``, the trigger, then we potentially want to teleport.
  395. First, we check to see if ``teleport_button_down`` is ``true``. If it is, that means the player is intending to teleport, while if it is ``false``, the player
  396. has simply released the trigger while holding a object.
  397. We then check to see if this controller has a teleport position, and we check to make sure the teleport mesh is visible.
  398. If both of those conditions are ``true``, we then calculate the offset the :ref:`ARVRCamera <class_ARVRCamera>` has from the :ref:`ARVROrigin <class_ARVROrigin>`. We do this
  399. because of how :ref:`ARVRCamera <class_ARVRCamera>` and :ref:`ARVROrigin <class_ARVROrigin>` work with room scale tracking.
  400. Because we want to teleport the player in their current position to the teleport position, and remember because of room scale tracking their current position can be offset from
  401. the origin, we have to figure out that offset so when we teleport we can remove it so that player's current position is teleported to the teleport position.
  402. We set the Y value of the camera_offset to zero because we do not want to account for offsets in the player's height.
  403. Then we teleport the :ref:`ARVROrigin <class_ARVROrigin>` to the teleport position, applying the camera offset.
  404. Regardless of whether we teleported or not, we reset all of the teleport related variables so the controller has to get new ones before teleporting again.
  405. _________
  406. Finally, let's look at ``sleep_area_entered`` and ``sleep_area_exited``.
  407. When a body enters or exists the sleep area, we check to see if it has a variable called ``can_sleep``. If it does, we then set it to ``false`` and wake the body if it has entered
  408. the sleep area, while if it has exited we set it to ``true`` so the :ref:`RigidBody <class_RigidBody>` nodes can sleep (and so we save some performance!)
  409. _________
  410. Okay, phew! That was a lot of code! Add the same script, ``VR_Controller.gd`` to the other controller so both controllers have the same script.
  411. Now go ahead and try the game again, and you should find you can teleport around by pressing the touch pad, and can grab and throw objects
  412. using the grab/grip buttons.
  413. Now, you may want to try moving using the trackpads and/or joysticks, but **it may make you motion sick!**
  414. One of the main reasons this can make you feel motion sick is because your vision tells you that you are moving, while your body is not moving.
  415. This conflict of signals makes the body feel sick, so lets fix it!
  416. Reducing motion sickness
  417. ------------------------
  418. .. note:: There are plenty of ways to reduce motion sickness in VR, and there is no one perfect way to reduce motion sickness. See:
  419. https://developer.oculus.com/design/latest/concepts/bp-locomotion/ for more information on how to implement locomotion, and how to
  420. reduce motion sickness.
  421. To help reduce motion sickness while moving, we are going to add a vignette effect that will only be visible while the player moves.
  422. Open up ``Movement_Vignette.tscn``, which you can find in the ``Scenes`` folder. Notice how it is just a :ref:`ColorRect <class_ColorRect>` node with a custom
  423. shader. Feel free to look at the custom shader if you want, it is just a slightly modified version of the vignette shader you can find in the Godot demo repository.
  424. With ``Movement_Vignette`` selected, make a new script called ``Movement_Vignette.gd``. Add the following code to ``Movement_Vignette.gd``:
  425. ::
  426. extends Control
  427. var controller_one
  428. var controller_two
  429. func _ready():
  430. yield(get_tree(), "idle_frame")
  431. yield(get_tree(), "idle_frame")
  432. yield(get_tree(), "idle_frame")
  433. yield(get_tree(), "idle_frame")
  434. var interface = ARVRServer.get_primary_interface()
  435. rect_size = interface.get_render_targetsize()
  436. rect_position = Vector2(0,0)
  437. controller_one = get_parent().get_node("Left_Controller")
  438. controller_two = get_parent().get_node("Right_Controller")
  439. visible = false
  440. func _process(delta):
  441. if (controller_one == null or controller_two == null):
  442. return
  443. if (controller_one.directional_movement == true or controller_two.directional_movement == true):
  444. visible = true
  445. else:
  446. visible = false
  447. Because this script is fairly simple, let's quickly go over what it does.
  448. In ``_ready``, we wait for four frames. We do this to ensure the VR interface is ready and going.
  449. Next, we get the current VR interface, and resize the :ref:`ColorRect <class_ColorRect>` node's size and position so that it covers the entire view in VR.
  450. Then we get the left and right controllers, assigning them to ``controller_one`` and ``controller_two``.
  451. We then make the vignette invisible by default.
  452. In ``_process`` we check to see if either of the controllers are moving the player by checking ``directional_movement``. If either controller is moving the player,
  453. we make the vignette visible, while if neither controller is moving the player, we make the vignette invisible.
  454. _________
  455. With that done, go ahead and try moving around with the joystick and/or the trackpad. You should find it is much less motion sickness inducing than before!
  456. Let's add some special :ref:`RigidBody <class_RigidBody>` nodes we can interact with next.
  457. Adding destroyable targets
  458. --------------------------
  459. First, let's start by making some targets we will destroy in various different ways with various different special :ref:`RigidBody <class_RigidBody>` nodes.
  460. Open up ``Sphere_Target.tscn``, which you can find in the ``Scenes`` folder. ``Sphere.tscn`` is just a :ref:`StaticBody <class_StaticBody>`
  461. with a :ref:`CollisionShape <class_CollisionShape>`, a mesh, and a audio player.
  462. Select the ``Sphere_Target`` root node, the :ref:`StaticBody <class_StaticBody>` node, and make a new script called ``Sphere_Target.gd``. Add the following
  463. to ``Sphere_Target.gd``:
  464. ::
  465. extends Spatial
  466. var destroyed = false
  467. var destroyed_timer = 0
  468. const DESTROY_WAIT_TIME = 80
  469. var health = 80
  470. const RIGID_BODY_TARGET = preload("res://Assets/RigidBody_Sphere.scn")
  471. func _ready():
  472. set_physics_process(false)
  473. func _physics_process(delta):
  474. destroyed_timer += delta
  475. if destroyed_timer >= DESTROY_WAIT_TIME:
  476. queue_free()
  477. func damage(bullet_global_transform, damage):
  478. if destroyed == true:
  479. return
  480. health -= damage
  481. if health <= 0:
  482. get_node("CollisionShape").disabled = true
  483. get_node("Shpere_Target").visible = false
  484. var clone = RIGID_BODY_TARGET.instance()
  485. add_child(clone)
  486. clone.global_transform = global_transform
  487. destroyed = true
  488. set_physics_process(true)
  489. get_node("AudioStreamPlayer").play()
  490. get_tree().root.get_node("Game").remove_sphere()
  491. Let's go over how this script works, starting with the class variables.
  492. - ``destroyed`` : A variable to track if this target is destroyed or not.
  493. - ``destroyed_timer`` : A variable to track how long the target has been destroyed.
  494. - ``DESTROY_WAIT_TIME`` : A constant to tell the sphere target how long to wait before destroying/deleting itself.
  495. - ``health`` : The amount of health the target has.
  496. - ``RIGID_BODY_TARGET`` : The target broken into several smaller :ref:`RigidBody <class_RigidBody>` nodes.
  497. ________
  498. Let's go over ``_ready``.
  499. All we are doing in ``_ready`` is setting ``_physics_process`` to ``false``. This is because we will only use ``_physics_process``
  500. for destroying the target, so we do not want to call it until the target is broken.
  501. ________
  502. Next, let's go over ``_physics_process``.
  503. First we add time to ``destroyed_timer``. Then we check to see if enough time has passed and we can destroy the target. If enough time has
  504. passed, we free/destroy the target using ``queue_free``.
  505. ________
  506. Finally, let's go over ``damage``.
  507. First, we check to make sure the target has not already been destroyed.
  508. Then, we remove however much damage the target has taken from the target's health.
  509. If the target has zero or less health, then it has taken enough damage to break.
  510. First, we disable the collision shape and make the whole target mesh invisible.
  511. Next, we spawn/instance the :ref:`RigidBody <class_RigidBody>` version of the target, and instance it at this target's position.
  512. Then we set ``destroyed`` to ``true`` and start processing ``_physics_process``.
  513. Finally, we play a sound, and remove a sphere from ``Game.gd`` by calling ``remove_sphere``.
  514. ________
  515. Now, you may have noticed we are calling a function in ``Game.gd`` we have not made yet, so let's fix that!
  516. First, open up ``Game.gd`` and add the following additional class variables:
  517. ::
  518. var spheres_left = 10
  519. var sphere_ui = null
  520. - ``spheres_left`` : The amount of sphere targets left in the game world.
  521. - ``sphere_ui`` : A reference to the sphere UI. We will use this later!
  522. Next, we need to add the ``remove_sphere`` function. Add the following to ``Game.gd``:
  523. ::
  524. func remove_sphere():
  525. spheres_left -= 1
  526. if sphere_ui != null:
  527. sphere_ui.update_ui(spheres_left)
  528. What this function does is it removes one from ``spheres_left``.
  529. Then it checks to see if ``sphere_ui`` is not null, and if it is not, then it calls it's ``update_ui`` function, passing in the amount of sphere's left.
  530. We'll add the UI code later in this part.
  531. Now that we have destroyable targets, we need a way to destroy them!
  532. Adding a pistol
  533. ---------------
  534. Okay, let's add a simple pistol.
  535. Open up ``Pistol.tscn``, which you will find in the ``Scenes`` folder.
  536. There is a few things to note here.
  537. The first thing to note is how everything is rotated. This is to make the pistol rotate correctly when the player grabs it. The other thing to notice is
  538. how there is a laser sight mesh, and a flash mesh, both of these do what you'd expect: act as a laser pointer and act as a muzzle flash respectively.
  539. The other thing to notice is how there is a :ref:`Raycast <class_Raycast>` node at the end of the pistol. This is what we will be using to calculate where the bullets impact.
  540. Now that we have looked at the scene, let's write the code. Select the ``Pistol`` root node, the :ref:`RigidBody <class_RigidBody>` node, and make a new
  541. script called ``Pistol.gd``. Add the following code to ``Pistol.gd``:
  542. ::
  543. extends RigidBody
  544. var flash_mesh
  545. const FLASH_TIME = 0.25
  546. var flash_timer = 0
  547. var laser_sight_mesh
  548. var raycast
  549. var BULLET_DAMAGE = 20
  550. func _ready():
  551. flash_mesh = get_node("Pistol_Flash")
  552. flash_mesh.visible = false
  553. laser_sight_mesh = get_node("LaserSight")
  554. laser_sight_mesh.visible = false
  555. raycast = get_node("RayCast")
  556. func _physics_process(delta):
  557. if flash_timer > 0:
  558. flash_timer -= delta
  559. # If the flash has been visible enough, then make the flash mesh invisible.
  560. if flash_timer <= 0:
  561. flash_mesh.visible = false
  562. # Called when the interact button is pressed while the object is held.
  563. func interact():
  564. if flash_timer <= 0:
  565. flash_timer = FLASH_TIME
  566. flash_mesh.visible = true
  567. raycast.force_raycast_update()
  568. if raycast.is_colliding():
  569. var body = raycast.get_collider()
  570. if body.has_method("damage"):
  571. body.damage(raycast.global_transform, BULLET_DAMAGE)
  572. elif body.has_method("apply_impulse"):
  573. var direction_vector = raycast.global_transform.basis.z.normalized()
  574. body.apply_impulse((raycast.global_transform.origin - body.global_transform.origin).normalized(), direction_vector * 1.2)
  575. get_node("AudioStreamPlayer3D").play()
  576. # Called when the object is picked up.
  577. func picked_up():
  578. laser_sight_mesh.visible = true
  579. # Called when the object is dropped.
  580. func dropped():
  581. laser_sight_mesh.visible = false
  582. Let's go over what this script does, starting with the class variables:
  583. - ``flash_mesh`` : The mesh used to make the muzzle flash.
  584. - ``FLASH_TIME`` : The length of time the muzzle flash is visible.
  585. - ``flash_timer``: A variable to track how long the muzzle flash has been visible.
  586. - ``laser_sight_mesh``: A long rectangular mesh used for the laser sight.
  587. - ``raycast``: The raycast node used for the pistol firing.
  588. - ``BULLET_DAMAGE``: The amount of damage a single bullet does.
  589. ________
  590. Let's go over ``_ready``.
  591. All we are doing here is getting the nodes and assigning them to the proper variables. We also make sure the flash and laser
  592. sight meshes are invisible.
  593. ________
  594. Next, let's look at ``_physics_process``.
  595. First, we check to see if the flash is visible. We do this by checking to see if ``flash_timer`` is more than zero. This is because ``flash_timer`` will be a inverted timer,
  596. a timer that counts down instead of counting up.
  597. If ``flash_timer`` is more than zero, we remove ``delta`` from it and check to see if it is equal to zero or less.
  598. If it is, we make the flash mesh invisible.
  599. This makes it where the flash mesh becomes invisible after ``FLASH_TIME`` many seconds has gone by.
  600. ________
  601. Now let's look at ``interact``, which is called when the trigger button on the VR controller is pressed and the pistol is being held.
  602. First, we check to see if the flash timer is less than or equal to zero. This check makes it where we cannot fire when the flash is visible, limiting how many bullets
  603. the pistol can fire.
  604. If we can fire, we reset ``flash_timer`` by setting it to ``FLASH_TIME``, and we make the flash mesh visible.
  605. We then update the :ref:`Raycast <class_Raycast>` and check to see if it is colliding with anything.
  606. If the :ref:`Raycast <class_Raycast>` is colliding with something, we get the collider. We check to see if the collider has the ``damage`` function, and if it does we call it.
  607. If it does not, we then check to see if the collider has the ``apply_impulse`` function, and if it does, we call it after calculating the direction from the
  608. :ref:`Raycast <class_Raycast>` to the collider.
  609. Finally, regardless of whether the pistol hit something or not, we play the pistol firing sound.
  610. ________
  611. Finally, let's look at ``picked_up`` and ``dropped``, which are called when the pistol is picked up and dropped respectively.
  612. All we are doing in these functions is making the laser pointer visible when the pistol is picked up, and making it invisible when the pistol is dropped.
  613. ________
  614. .. image:: img/starter_vr_tutorial_pistol.png
  615. With that done, go ahead and give the game a try! If you climb up the stairs and grab the pistols, you should be able to fire at the spheres and they will break!
  616. Adding a shotgun
  617. ----------------
  618. Let's add a different type of shooting :ref:`RigidBody <class_RigidBody>`: A shotgun. This is fairly simple to do, and almost everything is the same as the pistol.
  619. Open up ``Shotgun.tscn``, which you can find in ``Scenes``. Notice how everything is more or less the same, but instead of a single :ref:`Raycast <class_Raycast>`,
  620. there are five, and there is no laser pointer.
  621. This is because a shotgun generally fires in a cone shape, and so we are going to emulate that by having several :ref:`Raycast <class_Raycast>` nodes, all rotated randomly
  622. in a cone shape, and for fun I removed the laser pointer so the player has to aim without knowing for sure where the shotgun is pointing.
  623. Alright, select the ``Shotgun`` root node, the :ref:`RigidBody <class_RigidBody>` and make a new script called ``Shotgun.gd``. Add the following to ``Shotgun.gd``:
  624. ::
  625. extends RigidBody
  626. var flash_mesh
  627. const FLASH_TIME = 0.25
  628. var flash_timer = 0
  629. var raycasts
  630. var BULLET_DAMAGE = 30
  631. func _ready():
  632. flash_mesh = get_node("Shotgun_Flash")
  633. flash_mesh.visible = false
  634. raycasts = get_node("Raycasts")
  635. func _physics_process(delta):
  636. if flash_timer > 0:
  637. flash_timer -= delta
  638. if flash_timer <= 0:
  639. flash_mesh.visible = false
  640. # Called when the interact button is pressed while the object is held.
  641. func interact():
  642. if flash_timer <= 0:
  643. flash_timer = FLASH_TIME
  644. flash_mesh.visible = true
  645. for raycast in raycasts.get_children():
  646. raycast.rotation_degrees = Vector3(90 + rand_range(10, -10), 0, rand_range(10, -10))
  647. raycast.force_raycast_update()
  648. if raycast.is_colliding():
  649. var body = raycast.get_collider()
  650. # If the body has the damage method, then use that, otherwise use apply_impulse.
  651. if body.has_method("damage"):
  652. body.damage(raycast.global_transform, BULLET_DAMAGE)
  653. elif body.has_method("apply_impulse"):
  654. var direction_vector = raycast.global_transform.basis.z.normalized()
  655. body.apply_impulse((raycast.global_transform.origin - body.global_transform.origin).normalized(), direction_vector * 4)
  656. get_node("AudioStreamPlayer3D").play()
  657. func picked_up():
  658. pass
  659. func dropped():
  660. pass
  661. You may have noticed this is almost exactly the same as the pistol, and indeed it is, so let's only go over what has changed.
  662. - ``raycasts``: The node that holds all of the five :ref:`Raycast <class_Raycast>` nodes used for the shotgun's firing.
  663. In ``_ready``, we get the ``Raycasts`` node, instead of just a single :ref:`Raycast <class_Raycast>`.
  664. The only other change, besides there being nothing in ``picked_up`` and ``dropped`` is in ``interact``.
  665. Now we go through each :ref:`Raycast <class_Raycast>` in ``raycasts``. We then rotate it on the X and Z axis, making within a ``10`` to ``-10`` cone.
  666. From there, we process each :ref:`Raycast <class_Raycast>` like we did the single :ref:`Raycast <class_Raycast>` in the pistol, nothing changed at all,
  667. we are just doing it five times, once for each :ref:`Raycast <class_Raycast>` in ``raycasts``.
  668. ________
  669. Now you can find and fire the shotgun too! The shotgun is located around the back behind one of the walls (not in the building though!)
  670. Adding a bomb
  671. -------------
  672. While both of those are well and good, let's add something we can throw next! Let's add a bomb!
  673. Open up ``Bomb.tscn``, which you will find in the ``Scenes`` folder.
  674. First, notice how there is a rather large :ref:`Area <class_Area>` node. This is the explosion radius for the bomb. Anything within this :ref:`Area <class_Area>` will be
  675. effected by the explosion when the bomb explodes.
  676. The other thing to note is how there are two sets of :ref:`Particles <class_Particles>`: One for smoke coming out of the fuse, and another for the explosion itself.
  677. Feel free to take a look at the :ref:`Particles <class_Particles>` nodes if you want!
  678. The only thing to notice his how long the explosion :ref:`Particles <class_Particles>` node will last, their lifetime, which is 0.75 seconds. We need to know this so we can time
  679. the removal of the bomb with the end of the explosion :ref:`Particles <class_Particles>`.
  680. Alright, now let's write the code for the bomb. Select the ``Bomb`` :ref:`RigidBody <class_RigidBody>` node and make a new script called ``Bomb.gd``. Add the following code to
  681. ``Bomb.gd``:
  682. ::
  683. extends RigidBody
  684. var bomb_mesh
  685. const FUSE_TIME = 4
  686. var fuse_timer = 0
  687. var explosion_area
  688. var EXPLOSION_DAMAGE = 100
  689. var EXPLOSION_TIME = 0.75
  690. var explosion_timer = 0
  691. var explode = false
  692. var fuse_particles
  693. var explosion_particles
  694. var controller = null
  695. func _ready():
  696. bomb_mesh = get_node("Bomb")
  697. explosion_area = get_node("Area")
  698. fuse_particles = get_node("Fuse_Particles")
  699. explosion_particles = get_node("Explosion_Particles")
  700. set_physics_process(false)
  701. func _physics_process(delta):
  702. if fuse_timer < FUSE_TIME:
  703. fuse_timer += delta
  704. if fuse_timer >= FUSE_TIME:
  705. fuse_particles.emitting = false
  706. explosion_particles.one_shot = true
  707. explosion_particles.emitting = true
  708. bomb_mesh.visible = false
  709. collision_layer = 0
  710. collision_mask = 0
  711. mode = RigidBody.MODE_STATIC
  712. for body in explosion_area.get_overlapping_bodies():
  713. if body == self:
  714. pass
  715. else:
  716. if body.has_method("damage"):
  717. body.damage(global_transform.looking_at(body.global_transform.origin, Vector3(0,1,0)), EXPLOSION_DAMAGE)
  718. elif body.has_method("apply_impulse"):
  719. var direction_vector = body.global_transform.origin - global_transform.origin
  720. body.apply_impulse(direction_vector.normalized(), direction_vector.normalized() * 1.8)
  721. explode = true
  722. get_node("AudioStreamPlayer3D").play()
  723. if explode:
  724. explosion_timer += delta
  725. if explosion_timer >= EXPLOSION_TIME:
  726. explosion_area.monitoring = false
  727. if controller != null:
  728. controller.held_object = null
  729. controller.hand_mesh.visible = true
  730. if controller.grab_mode == "RAYCAST":
  731. controller.grab_raycast.visible = true
  732. queue_free()
  733. func interact():
  734. set_physics_process(true)
  735. fuse_particles.emitting = true
  736. func picked_up():
  737. pass
  738. func dropped():
  739. pass
  740. Let's go through what this script does, starting with the class variables:
  741. - ``bomb_mesh``: The :ref:`MeshInstance <class_MeshInstance>` used for the bomb mesh.
  742. - ``FUSE_TIME``: The length of time the fuse burns for.
  743. - ``fuse_timer``: A variable for tracking how long the fuse has been burning.
  744. - ``explosion_area``: The :ref:`Area <class_Area>` node used for detecting what nodes are inside the explosion.
  745. - ``EXPLOSION_DAMAGE``: The amount of damage the explosion does.
  746. - ``EXPLOSION_TIME``: The length of time the explosion :ref:`Particles <class_Particles>` take (you can calculate this number by multiplying the particles ``lifetime`` by it's ``speed scale``)
  747. - ``explosion_timer``: A variable for tracking how long the explosion has lasted.
  748. - ``explode``: A boolean for tracking whether the bomb has exploded.
  749. - ``fuse_particles``: The fuse :ref:`Particles <class_Particles>` node.
  750. - ``explosion_particles``: The explosion :ref:`Particles <class_Particles>` node.
  751. - ``controller``: The controller that is currently holding the bomb, if there is one. This is set by the controller, so we do not need to check anything outside of checking if it is ``null``.
  752. ________
  753. Let's go through ``_ready``.
  754. First, we get all of the nodes and assign them to the proper variables for later use.
  755. Then, we make sure ``_physics_process`` is not going to be called. We do this since we will be using ``_physics_process`` only for the fuse and
  756. for destroying the bomb, so we do not want to trigger that early, we only want the fuse to start when the player interacts while holding a bomb.
  757. ________
  758. Now let's look at ``_physics_process``.
  759. First we check to see if ``fuse_timer`` is less than ``FUSE_TIME``. If ``fuse_timer`` is less than ``FUSE_TIME``, then the bomb must be burning down the fuse.
  760. We then add time to ``fuser_timer``, and check to see if the bomb has waited long enough and has burned through the entire fuse.
  761. If the bomb has waited long enough, then we need to explode the bomb. We do this first by stopping the smoke :ref:`Particles <class_Particles>` from emitting, and
  762. making the explosion :ref:`Particles <class_Particles>` emit. We also hide the bomb mesh so it is no longer visible.
  763. Next, we make the set the collision layer and mask to zero, and set the :ref:`RigidBody <class_RigidBody>` mode to static. This makes it where the now exploded bomb cannot
  764. interact with the physics world, and so it will stay in place.
  765. Then we go through everything inside the explosion :ref:`Area <class_Area>`. We make sure the bodies inside the explosion :ref:`Area <class_Area>` are not the bomb itself, since we
  766. do not want to explode the bomb with itself. We then check to see if the bodies have the ``damage`` method/function, and if it does we call that, while if it does not we check to
  767. see if it has the ``apply_impulse`` method/function, and call that instead.
  768. Then we set ``explode`` to true since the bomb has exploded, and we play a sound.
  769. Next we check to see if the bomb has exploded, as we need to wait until the explosion :ref:`Particles <class_Particles>` are done.
  770. If the bomb has exploded, we add time to ``explosion_timer``. We then check to see if the explosion :ref:`Particles <class_Particles>` are done. If they are, we set the explosion
  771. :ref:`Area <class_Area>`'s monitoring property to ``false`` to ensure we do not get any bugs in the debugger, we make the controller drop the bomb if it is holding onto it,
  772. we make the grab :ref:`Raycast <class_Raycast>` visible if the grab mode is ``RAYCAST``, and we free/destroy the bomb using ``queue_free``.
  773. ________
  774. Finally, let's look at ``interact``.
  775. All we are doing here is making it where ``_physics_process`` will be called, which will start the fuse.
  776. We also make the fuse :ref:`Particles <class_Particles>` start emitting, so smoke comes out the top of the bomb.
  777. ________
  778. With that done, the bombs are ready to go! You can find them in the orange building. Because of how we are calculating velocity, it is easiest to throw bombs in a trusting like
  779. motion as opposed to a more natural throwing like motion. The smooth curve of a throwing like motion is harder to track, and the because of how we are tracking velocity it does
  780. not always work.
  781. Adding a sword
  782. --------------
  783. Finally, let's add a sword so we can slice through things!
  784. Open up ``Sword.tscn``, which you will find in ``Scenes``.
  785. There is not a whole lot to note here, but there is just one thing, and that is how the length of the blade of the sword is broken into several small :ref:`Area <class_Area>` nodes.
  786. This is because we need to roughly know where on the blade the sword collided, and this is the easiest (and only) way I could figure out how to do this.
  787. .. tip:: If you know how to find the point where a :ref:`Area <class_Area>` and a :ref:`CollisionObject <class_CollisionObject>` meet, please let me know and/or make a PR on the
  788. Godot documentation! This method of using several small :ref:`Area <class_Area>` nodes works okay, but it is not ideal.
  789. Other than that, there really is not much of note, so let's write the code. Select the ``Sword`` root node, the :ref:`RigidBody <class_RigidBody>` and make a new script called
  790. ``Sword.gd``. Add the following code to ``Sword.gd``:
  791. ::
  792. extends RigidBody
  793. const SWORD_DAMAGE = 20
  794. var controller
  795. func _ready():
  796. get_node("Damage_Area_01").connect("body_entered", self, "body_entered_sword", ["01"])
  797. get_node("Damage_Area_02").connect("body_entered", self, "body_entered_sword", ["02"])
  798. get_node("Damage_Area_03").connect("body_entered", self, "body_entered_sword", ["03"])
  799. get_node("Damage_Area_04").connect("body_entered", self, "body_entered_sword", ["04"])
  800. # Called when the interact button is pressed while the object is held.
  801. func interact():
  802. pass
  803. # Called when the object is picked up.
  804. func picked_up():
  805. pass
  806. # Called when the object is dropped.
  807. func dropped():
  808. pass
  809. func body_entered_sword(body, number):
  810. if body == self:
  811. pass
  812. else:
  813. var sword_part = null
  814. if number == "01":
  815. sword_part = get_node("Damage_Area_01")
  816. elif number == "02":
  817. sword_part = get_node("Damage_Area_02")
  818. elif number == "03":
  819. sword_part = get_node("Damage_Area_03")
  820. elif number == "04":
  821. sword_part = get_node("Damage_Area_04")
  822. if body.has_method("damage"):
  823. body.damage(sword_part.global_transform.looking_at(body.global_transform.origin, Vector3(0, 1, 0)), SWORD_DAMAGE)
  824. get_node("AudioStreamPlayer3D").play()
  825. elif body.has_method("apply_impulse"):
  826. var direction_vector = sword_part.global_transform.origin - body.global_transform.origin
  827. if controller == null:
  828. body.apply_impulse(direction_vector.normalized(), direction_vector.normalized() * self.linear_velocity)
  829. else:
  830. body.apply_impulse(direction_vector.normalized(), direction_vector.normalized() * controller.controller_velocity)
  831. get_node("AudioStreamPlayer3D").play()
  832. Let's go over what this script does, starting with the two class variables:
  833. - ``SWORD_DAMAGE`` : The amount of damage a single sword slice does.
  834. - ``controller`` : The controller that is holding the sword, if there is one. This is set by the controller, so we do not need to set it here in ``Sword.gd``.
  835. ________
  836. Let's go over ``_ready`` next.
  837. All we are doing here is connecting each of the :ref:`Area <class_Area>` nodes ``body_entered`` signal to the ``body_entered_sword`` function, passing in a additional argument
  838. which will be the number of the damage :ref:`Area <class_Area>`, so we can figure out where on the sword the body collided.
  839. ________
  840. Now let's go over ``body_entered_sword``.
  841. First, we make sure the body the sword has collided with is not itself.
  842. Then we figure out which part of the sword the body collided with, using the passed in number.
  843. Next, we check to see if the body the sword collided with has the ``damage`` function, and if it does, we call it and play a sound.
  844. If it does not have the damage function, we then check to see if it has the ``apply_impulse`` function. If it does, we then calculation the direction from the sword part the
  845. body collided with to the body. We then check to see if the sword is being held or not.
  846. If the sword is not being held, we use the :ref:`RigidBody <class_RigidBody>`'s velocity as the force in ``apply_impulse``, while if the sword is being held, we use the
  847. controller's velocity as the force in the impulse.
  848. Finally, we play a sound.
  849. ________
  850. .. image:: img/starter_vr_tutorial_sword.png
  851. With that done, you can now slice through the targets! You can find the sword in the corner in between the shotgun and the pistol.
  852. Updating the target UI
  853. ----------------------
  854. Okay, let's update the UI as the sphere targets are destroyed.
  855. Open up ``Game.tscn`` and then expand the ``GUI`` :ref:`MeshInstance <class_MeshInstance>`. From there, expand the ``GUI`` :ref:`Viewport <class_Viewport>` node
  856. and then select the ``base_control`` node. Add a new script called ``Base_Control``, and add the following:
  857. ::
  858. extends Control
  859. var sphere_count_label
  860. func _ready():
  861. sphere_count_label = get_node("Label_Sphere_Count")
  862. get_tree().root.get_node("Game").sphere_ui = self
  863. func update_ui(sphere_count):
  864. if sphere_count > 0:
  865. sphere_count_label.text = str(sphere_count) + " Spheres remaining"
  866. else:
  867. sphere_count_label.text = "No spheres remaining! Good job!"
  868. Let's go over what this script does quickly, as it is fairly simple.
  869. First, in ``_ready``, we get the :ref:`Label <class_Label>` that shows how many spheres are left and assign it to the ``sphere_count_label`` class variable.
  870. Next, we get ``Game.gd`` by using ``get_tree().root`` and assign ``sphere_ui`` to this script.
  871. In ``update_ui`` we change the sphere :ref:`Label <class_Label>`'s text. If there is at least one sphere remaining, we change the text to show how many sphere's are still
  872. left in the world. If there is not any more spheres left remaining, we change the text and congratulate the player.
  873. Adding the final special RigidBody
  874. ----------------------------------
  875. Finally, before we finish this tutorial, let's add a way to reset the game while in VR.
  876. Open up ``Reset_Box.tscn``, which you will find in ``Scenes``. Select the ``Reset_Box`` :ref:`RigidBody <class_RigidBody>` node and make a new script called ``Reset_Box.gd``.
  877. Add the following code to ``Reset_Box.gd``:
  878. ::
  879. extends RigidBody
  880. var start_transform
  881. var reset_timer = 0
  882. const RESET_TIME = 120
  883. func _ready():
  884. start_transform = global_transform
  885. func _physics_process(delta):
  886. reset_timer += delta
  887. if reset_timer >= RESET_TIME:
  888. global_transform = start_transform
  889. reset_timer = 0
  890. # Called when the interact button is pressed while the object is held.
  891. func interact():
  892. get_tree().change_scene("res://Game.tscn")
  893. # Called when the object is picked up.
  894. func picked_up():
  895. pass
  896. # Called when the object is dropped.
  897. func dropped():
  898. global_transform = start_transform
  899. reset_timer = 0
  900. Let's go over what this does quickly, as it is also fairly simple.
  901. First, we get the starting global :ref:`Transform <class_Transform>` in ``_ready``, and assign it to ``start_transform``. We will use this to reset the position of the reset box ever so often.
  902. In ``_physics_process`` we check to see if enough time has passed to reset. If it has, we reset the box's :ref:`Transform <class_Transform>` and then reset the timer.
  903. If the player interacts while holding the reset box, we reset the scene by calling ``get_tree().change_scene`` and passing in the path to the current scene. This resets/restarts
  904. the scene completely.
  905. When the reset box is dropped, we reset the :ref:`Transform <class_Transform>` and timer.
  906. ________
  907. With that done, when you grab and interact with the reset box, the entire scene will reset/restart and you can destroy all of the targets again!
  908. Final notes
  909. -----------
  910. .. image:: img/starter_vr_tutorial_sword.png
  911. Phew! That was a lot of work. Now you have a fairly simple VR project!
  912. .. warning:: If you ever get lost, be sure to read over the code again!
  913. You can download the finished project for this part here: :download:`VR_Starter_Tutorial_Complete.zip <files/VR_Starter_Tutorial_Complete.zip>`
  914. This hopefully will serve as a introduction into making fully featured VR games in Godot! The code written here can be expanded to make puzzle games, action games,
  915. story based games, and more!