CalibratableTracker.cs 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. using UnityEngine;
  2. namespace Tracking
  3. {
  4. public abstract class CalibratableTracker : MonoBehaviour
  5. {
  6. protected abstract string KeyPrefix { get; }
  7. private string KeyPosX => $"{KeyPrefix}_vive_tracker_pos_x";
  8. private string KeyPosY => $"{KeyPrefix}_vive_tracker_pos_y";
  9. private string KeyPosZ => $"{KeyPrefix}_vive_tracker_pos_z";
  10. private string KeyRotX => $"{KeyPrefix}_vive_tracker_rot_x";
  11. private string KeyRotY => $"{KeyPrefix}_vive_tracker_rot_y";
  12. private string KeyRotZ => $"{KeyPrefix}_vive_tracker_rot_z";
  13. private Transform trackerTransform;
  14. private Vector3 zeroRot;
  15. private Vector3 zeroPos;
  16. public Transform bicycleTransform;
  17. public Vector3 RelativeRotation
  18. {
  19. get
  20. {
  21. var newVal = trackerTransform.localRotation.eulerAngles - zeroRot;
  22. var x = newVal.x;
  23. var y = newVal.y;
  24. var z = newVal.z;
  25. if (x > 180) x = -(360 - x);
  26. if (y > 180) y = -(360 - y);
  27. if (z > 180) z = -(360 - z);
  28. if (x < -180) x = -(-360 - x);
  29. if (y < -180) y = -(-360 - y);
  30. if (z < -180) z = -(-360 - z);
  31. return new Vector3(x, y, z);
  32. }
  33. }
  34. public Vector3 RelativePosition => trackerTransform == null ? Vector3.zero : trackerTransform.localPosition - zeroPos;
  35. public Vector3 ZeroRot => zeroRot;
  36. public Vector3 ZeroPos => zeroPos;
  37. private void Start()
  38. {
  39. trackerTransform = transform;
  40. if (PlayerPrefs.HasKey(KeyPosX) && PlayerPrefs.HasKey(KeyPosY) && PlayerPrefs.HasKey(KeyPosZ))
  41. {
  42. var x = PlayerPrefs.GetFloat(KeyPosX);
  43. var y = PlayerPrefs.GetFloat(KeyPosY);
  44. var z = PlayerPrefs.GetFloat(KeyPosZ);
  45. zeroPos = new Vector3(x, y, z);
  46. }
  47. if (PlayerPrefs.HasKey(KeyRotX) && PlayerPrefs.HasKey(KeyRotY) && PlayerPrefs.HasKey(KeyRotZ))
  48. {
  49. var x = PlayerPrefs.GetFloat(KeyRotX);
  50. var y = PlayerPrefs.GetFloat(KeyRotY);
  51. var z = PlayerPrefs.GetFloat(KeyRotZ);
  52. zeroRot = new Vector3(x, y, z);
  53. }
  54. }
  55. //sets current position as zero -> straighten handlebar and call this function
  56. public void Calibrate()
  57. {
  58. zeroRot = trackerTransform.localRotation.eulerAngles;
  59. zeroPos = trackerTransform.localPosition;
  60. PlayerPrefs.SetFloat(KeyRotX, zeroRot.x);
  61. PlayerPrefs.SetFloat(KeyRotY, zeroRot.y);
  62. PlayerPrefs.SetFloat(KeyRotZ, zeroRot.z);
  63. PlayerPrefs.SetFloat(KeyPosX, zeroPos.x);
  64. PlayerPrefs.SetFloat(KeyPosY, zeroPos.y);
  65. PlayerPrefs.SetFloat(KeyPosZ, zeroPos.z);
  66. PlayerPrefs.Save();
  67. }
  68. }
  69. }