BlueGit

blue-star ggj-2020

Files

ggj-2020 / Assets / Oculus / VR / Scripts / Util / OVRPlayerController.cs

OVRPlayerController.cs

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