GyroController.cs 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. using UnityEngine;
  2. using UnityEngine.UI;
  3. namespace Google.Maps.Examples.Shared {
  4. /// <summary>
  5. /// This class controls the pitch elevation of the camera rig when the examples
  6. /// are deployed on a mobile device.
  7. /// </summary>
  8. public class GyroController : MonoBehaviour {
  9. /// <summary>
  10. /// Reference to the camera rig (wraps the camera object)
  11. /// </summary>
  12. public Transform CameraRig;
  13. /// <summary>
  14. /// Text field for feedback on Gyro availability
  15. /// </summary>
  16. public Text InfoTxt;
  17. /// <summary>
  18. /// Keeps track of the euler rotation on the forward axis
  19. /// </summary>
  20. private float AngleX;
  21. /// <summary>
  22. /// Reference to the transform of the camera
  23. /// </summary>
  24. private Transform CameraTransform;
  25. /// <summary>
  26. /// Reference to the gyroscope when available
  27. /// </summary>
  28. private Gyroscope Gyro;
  29. /// <summary>
  30. /// Indicates if the gyroscope is supported on the device where the app is deployed
  31. /// </summary>
  32. private bool GyroSupported;
  33. /// <summary>
  34. /// At start, we detect the availability of the gyroscope and keep track of camera transform
  35. /// and euler rotation on the X axis.
  36. /// </summary>
  37. private void Start() {
  38. GyroSupported = SystemInfo.supportsGyroscope;
  39. if (GyroSupported) {
  40. Gyro = Input.gyro;
  41. Gyro.enabled = true;
  42. }
  43. if (CameraRig != null) {
  44. var c = CameraRig.gameObject.GetComponentInChildren<Camera>();
  45. if (c != null) {
  46. CameraTransform = c.transform;
  47. AngleX = CameraTransform.rotation.eulerAngles.x;
  48. }
  49. }
  50. if (InfoTxt != null) {
  51. InfoTxt.text = "";
  52. }
  53. }
  54. /// <summary>
  55. /// During updates, keep track of the rotation diffs around the X axis,
  56. /// and apply the new combined angle to the camera transform.
  57. /// </summary>
  58. private void Update() {
  59. if (GyroSupported) {
  60. if (CameraRig != null) {
  61. AngleX += -Input.gyro.rotationRateUnbiased.x;
  62. AngleX = Mathf.Clamp(AngleX, -30f, 90f);
  63. CameraTransform.transform.localRotation = Quaternion.Euler(
  64. AngleX,
  65. 0f,
  66. 0f);
  67. }
  68. } else {
  69. InfoTxt.text = "Gyro Not supported !";
  70. }
  71. }
  72. }
  73. }