Assignment for RMIT Mixed Reality in 2020
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

613 lines
18 KiB

  1. /************************************************************************************
  2. Copyright : Copyright (c) Facebook Technologies, LLC and its affiliates. All rights reserved.
  3. Licensed under the Oculus Utilities SDK License Version 1.31 (the "License"); you may not use
  4. the Utilities SDK except in compliance with the License, which is provided at the time of installation
  5. or download, or which otherwise accompanies this software in either electronic or hard copy form.
  6. You may obtain a copy of the License at https://developer.oculus.com/licenses/utilities-1.31
  7. Unless required by applicable law or agreed to in writing, the Utilities SDK distributed
  8. under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
  9. ANY KIND, either express or implied. See the License for the specific language governing
  10. permissions and limitations under the License.
  11. ************************************************************************************/
  12. using System;
  13. using UnityEngine;
  14. /// <summary>
  15. /// Controls the player's movement in virtual reality.
  16. /// </summary>
  17. [RequireComponent(typeof(CharacterController))]
  18. public class OVRPlayerController : MonoBehaviour
  19. {
  20. /// <summary>
  21. /// The rate acceleration during movement.
  22. /// </summary>
  23. public float Acceleration = 0.1f;
  24. /// <summary>
  25. /// The rate of damping on movement.
  26. /// </summary>
  27. public float Damping = 0.3f;
  28. /// <summary>
  29. /// The rate of additional damping when moving sideways or backwards.
  30. /// </summary>
  31. public float BackAndSideDampen = 0.5f;
  32. /// <summary>
  33. /// The force applied to the character when jumping.
  34. /// </summary>
  35. public float JumpForce = 0.3f;
  36. /// <summary>
  37. /// The rate of rotation when using a gamepad.
  38. /// </summary>
  39. public float RotationAmount = 1.5f;
  40. /// <summary>
  41. /// The rate of rotation when using the keyboard.
  42. /// </summary>
  43. public float RotationRatchet = 45.0f;
  44. /// <summary>
  45. /// The player will rotate in fixed steps if Snap Rotation is enabled.
  46. /// </summary>
  47. [Tooltip("The player will rotate in fixed steps if Snap Rotation is enabled.")]
  48. public bool SnapRotation = true;
  49. /// <summary>
  50. /// How many fixed speeds to use with linear movement? 0=linear control
  51. /// </summary>
  52. [Tooltip("How many fixed speeds to use with linear movement? 0=linear control")]
  53. public int FixedSpeedSteps;
  54. /// <summary>
  55. /// If true, reset the initial yaw of the player controller when the Hmd pose is recentered.
  56. /// </summary>
  57. public bool HmdResetsY = true;
  58. /// <summary>
  59. /// If true, tracking data from a child OVRCameraRig will update the direction of movement.
  60. /// </summary>
  61. public bool HmdRotatesY = true;
  62. /// <summary>
  63. /// Modifies the strength of gravity.
  64. /// </summary>
  65. public float GravityModifier = 0.379f;
  66. /// <summary>
  67. /// If true, each OVRPlayerController will use the player's physical height.
  68. /// </summary>
  69. public bool useProfileData = true;
  70. /// <summary>
  71. /// The CameraHeight is the actual height of the HMD and can be used to adjust the height of the character controller, which will affect the
  72. /// ability of the character to move into areas with a low ceiling.
  73. /// </summary>
  74. [NonSerialized]
  75. public float CameraHeight;
  76. /// <summary>
  77. /// This event is raised after the character controller is moved. This is used by the OVRAvatarLocomotion script to keep the avatar transform synchronized
  78. /// with the OVRPlayerController.
  79. /// </summary>
  80. public event Action<Transform> TransformUpdated;
  81. /// <summary>
  82. /// This bool is set to true whenever the player controller has been teleported. It is reset after every frame. Some systems, such as
  83. /// CharacterCameraConstraint, test this boolean in order to disable logic that moves the character controller immediately
  84. /// following the teleport.
  85. /// </summary>
  86. [NonSerialized] // This doesn't need to be visible in the inspector.
  87. public bool Teleported;
  88. /// <summary>
  89. /// This event is raised immediately after the camera transform has been updated, but before movement is updated.
  90. /// </summary>
  91. public event Action CameraUpdated;
  92. /// <summary>
  93. /// This event is raised right before the character controller is actually moved in order to provide other systems the opportunity to
  94. /// move the character controller in response to things other than user input, such as movement of the HMD. See CharacterCameraConstraint.cs
  95. /// for an example of this.
  96. /// </summary>
  97. public event Action PreCharacterMove;
  98. /// <summary>
  99. /// When true, user input will be applied to linear movement. Set this to false whenever the player controller needs to ignore input for
  100. /// linear movement.
  101. /// </summary>
  102. public bool EnableLinearMovement = true;
  103. /// <summary>
  104. /// When true, user input will be applied to rotation. Set this to false whenever the player controller needs to ignore input for rotation.
  105. /// </summary>
  106. public bool EnableRotation = true;
  107. /// <summary>
  108. /// Rotation defaults to secondary thumbstick. You can allow either here. Note that this won't behave well if EnableLinearMovement is true.
  109. /// </summary>
  110. public bool RotationEitherThumbstick = false;
  111. protected CharacterController Controller = null;
  112. protected OVRCameraRig CameraRig = null;
  113. private float MoveScale = 1.0f;
  114. private Vector3 MoveThrottle = Vector3.zero;
  115. private float FallSpeed = 0.0f;
  116. private OVRPose? InitialPose;
  117. public float InitialYRotation { get; private set; }
  118. private float MoveScaleMultiplier = 1.0f;
  119. private float RotationScaleMultiplier = 1.0f;
  120. private bool SkipMouseRotation = true; // It is rare to want to use mouse movement in VR, so ignore the mouse by default.
  121. private bool HaltUpdateMovement = false;
  122. private bool prevHatLeft = false;
  123. private bool prevHatRight = false;
  124. private float SimulationRate = 60f;
  125. private float buttonRotation = 0f;
  126. private bool ReadyToSnapTurn; // Set to true when a snap turn has occurred, code requires one frame of centered thumbstick to enable another snap turn.
  127. private bool playerControllerEnabled = false;
  128. void Start()
  129. {
  130. // Add eye-depth as a camera offset from the player controller
  131. var p = CameraRig.transform.localPosition;
  132. p.z = OVRManager.profile.eyeDepth;
  133. CameraRig.transform.localPosition = p;
  134. }
  135. void Awake()
  136. {
  137. Controller = gameObject.GetComponent<CharacterController>();
  138. if (Controller == null)
  139. Debug.LogWarning("OVRPlayerController: No CharacterController attached.");
  140. // We use OVRCameraRig to set rotations to cameras,
  141. // and to be influenced by rotation
  142. OVRCameraRig[] CameraRigs = gameObject.GetComponentsInChildren<OVRCameraRig>();
  143. if (CameraRigs.Length == 0)
  144. Debug.LogWarning("OVRPlayerController: No OVRCameraRig attached.");
  145. else if (CameraRigs.Length > 1)
  146. Debug.LogWarning("OVRPlayerController: More then 1 OVRCameraRig attached.");
  147. else
  148. CameraRig = CameraRigs[0];
  149. InitialYRotation = transform.rotation.eulerAngles.y;
  150. }
  151. void OnEnable()
  152. {
  153. }
  154. void OnDisable()
  155. {
  156. if (playerControllerEnabled)
  157. {
  158. OVRManager.display.RecenteredPose -= ResetOrientation;
  159. if (CameraRig != null)
  160. {
  161. CameraRig.UpdatedAnchors -= UpdateTransform;
  162. }
  163. playerControllerEnabled = false;
  164. }
  165. }
  166. void Update()
  167. {
  168. if (!playerControllerEnabled)
  169. {
  170. if (OVRManager.OVRManagerinitialized)
  171. {
  172. OVRManager.display.RecenteredPose += ResetOrientation;
  173. if (CameraRig != null)
  174. {
  175. CameraRig.UpdatedAnchors += UpdateTransform;
  176. }
  177. playerControllerEnabled = true;
  178. }
  179. else
  180. return;
  181. }
  182. //Use keys to ratchet rotation
  183. if (Input.GetKeyDown(KeyCode.Q))
  184. buttonRotation -= RotationRatchet;
  185. if (Input.GetKeyDown(KeyCode.E))
  186. buttonRotation += RotationRatchet;
  187. }
  188. protected virtual void UpdateController()
  189. {
  190. if (useProfileData)
  191. {
  192. if (InitialPose == null)
  193. {
  194. // Save the initial pose so it can be recovered if useProfileData
  195. // is turned off later.
  196. InitialPose = new OVRPose()
  197. {
  198. position = CameraRig.transform.localPosition,
  199. orientation = CameraRig.transform.localRotation
  200. };
  201. }
  202. var p = CameraRig.transform.localPosition;
  203. if (OVRManager.instance.trackingOriginType == OVRManager.TrackingOrigin.EyeLevel)
  204. {
  205. p.y = OVRManager.profile.eyeHeight - (0.5f * Controller.height) + Controller.center.y;
  206. }
  207. else if (OVRManager.instance.trackingOriginType == OVRManager.TrackingOrigin.FloorLevel)
  208. {
  209. p.y = -(0.5f * Controller.height) + Controller.center.y;
  210. }
  211. CameraRig.transform.localPosition = p;
  212. }
  213. else if (InitialPose != null)
  214. {
  215. // Return to the initial pose if useProfileData was turned off at runtime
  216. CameraRig.transform.localPosition = InitialPose.Value.position;
  217. CameraRig.transform.localRotation = InitialPose.Value.orientation;
  218. InitialPose = null;
  219. }
  220. CameraHeight = CameraRig.centerEyeAnchor.localPosition.y;
  221. if (CameraUpdated != null)
  222. {
  223. CameraUpdated();
  224. }
  225. UpdateMovement();
  226. Vector3 moveDirection = Vector3.zero;
  227. float motorDamp = (1.0f + (Damping * SimulationRate * Time.deltaTime));
  228. MoveThrottle.x /= motorDamp;
  229. MoveThrottle.y = (MoveThrottle.y > 0.0f) ? (MoveThrottle.y / motorDamp) : MoveThrottle.y;
  230. MoveThrottle.z /= motorDamp;
  231. moveDirection += MoveThrottle * SimulationRate * Time.deltaTime;
  232. // Gravity
  233. if (Controller.isGrounded && FallSpeed <= 0)
  234. FallSpeed = ((Physics.gravity.y * (GravityModifier * 0.002f)));
  235. else
  236. FallSpeed += ((Physics.gravity.y * (GravityModifier * 0.002f)) * SimulationRate * Time.deltaTime);
  237. moveDirection.y += FallSpeed * SimulationRate * Time.deltaTime;
  238. if (Controller.isGrounded && MoveThrottle.y <= transform.lossyScale.y * 0.001f)
  239. {
  240. // Offset correction for uneven ground
  241. float bumpUpOffset = Mathf.Max(Controller.stepOffset, new Vector3(moveDirection.x, 0, moveDirection.z).magnitude);
  242. moveDirection -= bumpUpOffset * Vector3.up;
  243. }
  244. if (PreCharacterMove != null)
  245. {
  246. PreCharacterMove();
  247. Teleported = false;
  248. }
  249. Vector3 predictedXZ = Vector3.Scale((Controller.transform.localPosition + moveDirection), new Vector3(1, 0, 1));
  250. // Move contoller
  251. Controller.Move(moveDirection);
  252. Vector3 actualXZ = Vector3.Scale(Controller.transform.localPosition, new Vector3(1, 0, 1));
  253. if (predictedXZ != actualXZ)
  254. MoveThrottle += (actualXZ - predictedXZ) / (SimulationRate * Time.deltaTime);
  255. }
  256. public virtual void UpdateMovement()
  257. {
  258. if (HaltUpdateMovement)
  259. return;
  260. if (EnableLinearMovement)
  261. {
  262. bool moveForward = Input.GetKey(KeyCode.W) || Input.GetKey(KeyCode.UpArrow);
  263. bool moveLeft = Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.LeftArrow);
  264. bool moveRight = Input.GetKey(KeyCode.D) || Input.GetKey(KeyCode.RightArrow);
  265. bool moveBack = Input.GetKey(KeyCode.S) || Input.GetKey(KeyCode.DownArrow);
  266. bool dpad_move = false;
  267. if (OVRInput.Get(OVRInput.Button.DpadUp))
  268. {
  269. moveForward = true;
  270. dpad_move = true;
  271. }
  272. if (OVRInput.Get(OVRInput.Button.DpadDown))
  273. {
  274. moveBack = true;
  275. dpad_move = true;
  276. }
  277. MoveScale = 1.0f;
  278. if ((moveForward && moveLeft) || (moveForward && moveRight) ||
  279. (moveBack && moveLeft) || (moveBack && moveRight))
  280. MoveScale = 0.70710678f;
  281. // No positional movement if we are in the air
  282. if (!Controller.isGrounded)
  283. MoveScale = 0.0f;
  284. MoveScale *= SimulationRate * Time.deltaTime;
  285. // Compute this for key movement
  286. float moveInfluence = Acceleration * 0.1f * MoveScale * MoveScaleMultiplier;
  287. // Run!
  288. if (dpad_move || Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift))
  289. moveInfluence *= 2.0f;
  290. Quaternion ort = transform.rotation;
  291. Vector3 ortEuler = ort.eulerAngles;
  292. ortEuler.z = ortEuler.x = 0f;
  293. ort = Quaternion.Euler(ortEuler);
  294. if (moveForward)
  295. MoveThrottle += ort * (transform.lossyScale.z * moveInfluence * Vector3.forward);
  296. if (moveBack)
  297. MoveThrottle += ort * (transform.lossyScale.z * moveInfluence * BackAndSideDampen * Vector3.back);
  298. if (moveLeft)
  299. MoveThrottle += ort * (transform.lossyScale.x * moveInfluence * BackAndSideDampen * Vector3.left);
  300. if (moveRight)
  301. MoveThrottle += ort * (transform.lossyScale.x * moveInfluence * BackAndSideDampen * Vector3.right);
  302. moveInfluence = Acceleration * 0.1f * MoveScale * MoveScaleMultiplier;
  303. #if !UNITY_ANDROID // LeftTrigger not avail on Android game pad
  304. moveInfluence *= 1.0f + OVRInput.Get(OVRInput.Axis1D.PrimaryIndexTrigger);
  305. #endif
  306. Vector2 primaryAxis = OVRInput.Get(OVRInput.Axis2D.PrimaryThumbstick);
  307. // If speed quantization is enabled, adjust the input to the number of fixed speed steps.
  308. if (FixedSpeedSteps > 0)
  309. {
  310. primaryAxis.y = Mathf.Round(primaryAxis.y * FixedSpeedSteps) / FixedSpeedSteps;
  311. primaryAxis.x = Mathf.Round(primaryAxis.x * FixedSpeedSteps) / FixedSpeedSteps;
  312. }
  313. if (primaryAxis.y > 0.0f)
  314. MoveThrottle += ort * (primaryAxis.y * transform.lossyScale.z * moveInfluence * Vector3.forward);
  315. if (primaryAxis.y < 0.0f)
  316. MoveThrottle += ort * (Mathf.Abs(primaryAxis.y) * transform.lossyScale.z * moveInfluence *
  317. BackAndSideDampen * Vector3.back);
  318. if (primaryAxis.x < 0.0f)
  319. MoveThrottle += ort * (Mathf.Abs(primaryAxis.x) * transform.lossyScale.x * moveInfluence *
  320. BackAndSideDampen * Vector3.left);
  321. if (primaryAxis.x > 0.0f)
  322. MoveThrottle += ort * (primaryAxis.x * transform.lossyScale.x * moveInfluence * BackAndSideDampen *
  323. Vector3.right);
  324. }
  325. if (EnableRotation)
  326. {
  327. Vector3 euler = transform.rotation.eulerAngles;
  328. float rotateInfluence = SimulationRate * Time.deltaTime * RotationAmount * RotationScaleMultiplier;
  329. bool curHatLeft = OVRInput.Get(OVRInput.Button.PrimaryShoulder);
  330. if (curHatLeft && !prevHatLeft)
  331. euler.y -= RotationRatchet;
  332. prevHatLeft = curHatLeft;
  333. bool curHatRight = OVRInput.Get(OVRInput.Button.SecondaryShoulder);
  334. if (curHatRight && !prevHatRight)
  335. euler.y += RotationRatchet;
  336. prevHatRight = curHatRight;
  337. euler.y += buttonRotation;
  338. buttonRotation = 0f;
  339. #if !UNITY_ANDROID || UNITY_EDITOR
  340. if (!SkipMouseRotation)
  341. euler.y += Input.GetAxis("Mouse X") * rotateInfluence * 3.25f;
  342. #endif
  343. if (SnapRotation)
  344. {
  345. if (OVRInput.Get(OVRInput.Button.SecondaryThumbstickLeft) ||
  346. (RotationEitherThumbstick && OVRInput.Get(OVRInput.Button.PrimaryThumbstickLeft)))
  347. {
  348. if (ReadyToSnapTurn)
  349. {
  350. euler.y -= RotationRatchet;
  351. ReadyToSnapTurn = false;
  352. }
  353. }
  354. else if (OVRInput.Get(OVRInput.Button.SecondaryThumbstickRight) ||
  355. (RotationEitherThumbstick && OVRInput.Get(OVRInput.Button.PrimaryThumbstickRight)))
  356. {
  357. if (ReadyToSnapTurn)
  358. {
  359. euler.y += RotationRatchet;
  360. ReadyToSnapTurn = false;
  361. }
  362. }
  363. else
  364. {
  365. ReadyToSnapTurn = true;
  366. }
  367. }
  368. else
  369. {
  370. Vector2 secondaryAxis = OVRInput.Get(OVRInput.Axis2D.SecondaryThumbstick);
  371. if (RotationEitherThumbstick)
  372. {
  373. Vector2 altSecondaryAxis = OVRInput.Get(OVRInput.Axis2D.PrimaryThumbstick);
  374. if (secondaryAxis.sqrMagnitude < altSecondaryAxis.sqrMagnitude)
  375. {
  376. secondaryAxis = altSecondaryAxis;
  377. }
  378. }
  379. euler.y += secondaryAxis.x * rotateInfluence;
  380. }
  381. transform.rotation = Quaternion.Euler(euler);
  382. }
  383. }
  384. /// <summary>
  385. /// Invoked by OVRCameraRig's UpdatedAnchors callback. Allows the Hmd rotation to update the facing direction of the player.
  386. /// </summary>
  387. public void UpdateTransform(OVRCameraRig rig)
  388. {
  389. Transform root = CameraRig.trackingSpace;
  390. Transform centerEye = CameraRig.centerEyeAnchor;
  391. if (HmdRotatesY && !Teleported)
  392. {
  393. Vector3 prevPos = root.position;
  394. Quaternion prevRot = root.rotation;
  395. transform.rotation = Quaternion.Euler(0.0f, centerEye.rotation.eulerAngles.y, 0.0f);
  396. root.position = prevPos;
  397. root.rotation = prevRot;
  398. }
  399. UpdateController();
  400. if (TransformUpdated != null)
  401. {
  402. TransformUpdated(root);
  403. }
  404. }
  405. /// <summary>
  406. /// Jump! Must be enabled manually.
  407. /// </summary>
  408. public bool Jump()
  409. {
  410. if (!Controller.isGrounded)
  411. return false;
  412. MoveThrottle += new Vector3(0, transform.lossyScale.y * JumpForce, 0);
  413. return true;
  414. }
  415. /// <summary>
  416. /// Stop this instance.
  417. /// </summary>
  418. public void Stop()
  419. {
  420. Controller.Move(Vector3.zero);
  421. MoveThrottle = Vector3.zero;
  422. FallSpeed = 0.0f;
  423. }
  424. /// <summary>
  425. /// Gets the move scale multiplier.
  426. /// </summary>
  427. /// <param name="moveScaleMultiplier">Move scale multiplier.</param>
  428. public void GetMoveScaleMultiplier(ref float moveScaleMultiplier)
  429. {
  430. moveScaleMultiplier = MoveScaleMultiplier;
  431. }
  432. /// <summary>
  433. /// Sets the move scale multiplier.
  434. /// </summary>
  435. /// <param name="moveScaleMultiplier">Move scale multiplier.</param>
  436. public void SetMoveScaleMultiplier(float moveScaleMultiplier)
  437. {
  438. MoveScaleMultiplier = moveScaleMultiplier;
  439. }
  440. /// <summary>
  441. /// Gets the rotation scale multiplier.
  442. /// </summary>
  443. /// <param name="rotationScaleMultiplier">Rotation scale multiplier.</param>
  444. public void GetRotationScaleMultiplier(ref float rotationScaleMultiplier)
  445. {
  446. rotationScaleMultiplier = RotationScaleMultiplier;
  447. }
  448. /// <summary>
  449. /// Sets the rotation scale multiplier.
  450. /// </summary>
  451. /// <param name="rotationScaleMultiplier">Rotation scale multiplier.</param>
  452. public void SetRotationScaleMultiplier(float rotationScaleMultiplier)
  453. {
  454. RotationScaleMultiplier = rotationScaleMultiplier;
  455. }
  456. /// <summary>
  457. /// Gets the allow mouse rotation.
  458. /// </summary>
  459. /// <param name="skipMouseRotation">Allow mouse rotation.</param>
  460. public void GetSkipMouseRotation(ref bool skipMouseRotation)
  461. {
  462. skipMouseRotation = SkipMouseRotation;
  463. }
  464. /// <summary>
  465. /// Sets the allow mouse rotation.
  466. /// </summary>
  467. /// <param name="skipMouseRotation">If set to <c>true</c> allow mouse rotation.</param>
  468. public void SetSkipMouseRotation(bool skipMouseRotation)
  469. {
  470. SkipMouseRotation = skipMouseRotation;
  471. }
  472. /// <summary>
  473. /// Gets the halt update movement.
  474. /// </summary>
  475. /// <param name="haltUpdateMovement">Halt update movement.</param>
  476. public void GetHaltUpdateMovement(ref bool haltUpdateMovement)
  477. {
  478. haltUpdateMovement = HaltUpdateMovement;
  479. }
  480. /// <summary>
  481. /// Sets the halt update movement.
  482. /// </summary>
  483. /// <param name="haltUpdateMovement">If set to <c>true</c> halt update movement.</param>
  484. public void SetHaltUpdateMovement(bool haltUpdateMovement)
  485. {
  486. HaltUpdateMovement = haltUpdateMovement;
  487. }
  488. /// <summary>
  489. /// Resets the player look rotation when the device orientation is reset.
  490. /// </summary>
  491. public void ResetOrientation()
  492. {
  493. if (HmdResetsY && !HmdRotatesY)
  494. {
  495. Vector3 euler = transform.rotation.eulerAngles;
  496. euler.y = InitialYRotation;
  497. transform.rotation = Quaternion.Euler(euler);
  498. }
  499. }
  500. }