vr_starter_tutorial.rst 67 KB

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