FixOrientation.cs 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. /*===============================================================================
  2. Copyright (C) 2022 Immersal - Part of Hexagon. All Rights Reserved.
  3. This file is part of the Immersal SDK.
  4. The Immersal SDK cannot be copied, distributed, or made available to
  5. third-parties for commercial purposes without written permission of Immersal Ltd.
  6. Contact sdk@immersal.com for licensing requests.
  7. ===============================================================================*/
  8. using UnityEngine;
  9. using System;
  10. namespace Immersal.Samples.Util
  11. {
  12. public class FixOrientation : MonoBehaviour {
  13. #if !UNITY_EDITOR
  14. private DeviceOrientation m_previousOrientation;
  15. private RectTransform m_rt;
  16. private float m_rotAngle = 0f;
  17. private bool m_bDoRotate = false;
  18. // Use this for initialization
  19. private void Awake () {
  20. m_rt = GetComponent<RectTransform>();
  21. }
  22. private void Start()
  23. {
  24. SetOrientation();
  25. }
  26. private void OnEnable()
  27. {
  28. SetOrientation();
  29. }
  30. void Update () {
  31. DeviceOrientation orientation = Input.deviceOrientation;
  32. if (orientation == DeviceOrientation.Unknown)
  33. return;
  34. if (orientation != m_previousOrientation)
  35. {
  36. m_previousOrientation = orientation;
  37. m_bDoRotate = true;
  38. switch (orientation)
  39. {
  40. case DeviceOrientation.LandscapeLeft:
  41. m_rotAngle = -90f;
  42. break;
  43. case DeviceOrientation.LandscapeRight:
  44. m_rotAngle = 90f;
  45. break;
  46. default:
  47. m_rotAngle = 0f;
  48. break;
  49. }
  50. }
  51. if (!m_bDoRotate)
  52. return;
  53. if (Math.Abs(m_rt.localEulerAngles.z - m_rotAngle) < 0.0001f)
  54. {
  55. m_rt.localEulerAngles = new Vector3(0, 0, m_rotAngle);
  56. m_bDoRotate = false;
  57. }
  58. else
  59. {
  60. Quaternion target = Quaternion.Euler(0, 0, m_rotAngle);
  61. m_rt.rotation = Quaternion.Slerp(m_rt.rotation, target, Time.deltaTime * 10f);
  62. }
  63. }
  64. void SetOrientation()
  65. {
  66. DeviceOrientation orientation = Input.deviceOrientation;
  67. switch (orientation)
  68. {
  69. case DeviceOrientation.LandscapeLeft:
  70. m_rotAngle = -90f;
  71. break;
  72. case DeviceOrientation.LandscapeRight:
  73. m_rotAngle = 90f;
  74. break;
  75. default:
  76. m_rotAngle = 0f;
  77. break;
  78. }
  79. m_rt.localEulerAngles = new Vector3(0, 0, m_rotAngle);
  80. m_previousOrientation = orientation;
  81. }
  82. #endif
  83. }
  84. }