1
0

CalibratableTracker.cs 3.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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. if(trackerTransform == null) return Vector3.zero; //TODO: something smarter
  22. var newVal = trackerTransform.localRotation.eulerAngles - zeroRot;
  23. var x = newVal.x;
  24. var y = newVal.y;
  25. var z = newVal.z;
  26. if (x > 180) x = -(360 - x);
  27. if (y > 180) y = -(360 - y);
  28. if (z > 180) z = -(360 - z);
  29. if (x < -180) x = -(-360 - x);
  30. if (y < -180) y = -(-360 - y);
  31. if (z < -180) z = -(-360 - z);
  32. return new Vector3(x, y, z);
  33. }
  34. }
  35. public Vector3 RelativePosition => trackerTransform == null ? Vector3.zero : trackerTransform.localPosition - zeroPos;
  36. public Vector3 ZeroRot => zeroRot;
  37. public Vector3 ZeroPos => zeroPos;
  38. private void Start()
  39. {
  40. trackerTransform = transform;
  41. if (PlayerPrefs.HasKey(KeyPosX) && PlayerPrefs.HasKey(KeyPosY) && PlayerPrefs.HasKey(KeyPosZ))
  42. {
  43. var x = PlayerPrefs.GetFloat(KeyPosX);
  44. var y = PlayerPrefs.GetFloat(KeyPosY);
  45. var z = PlayerPrefs.GetFloat(KeyPosZ);
  46. zeroPos = new Vector3(x, y, z);
  47. }
  48. if (PlayerPrefs.HasKey(KeyRotX) && PlayerPrefs.HasKey(KeyRotY) && PlayerPrefs.HasKey(KeyRotZ))
  49. {
  50. var x = PlayerPrefs.GetFloat(KeyRotX);
  51. var y = PlayerPrefs.GetFloat(KeyRotY);
  52. var z = PlayerPrefs.GetFloat(KeyRotZ);
  53. zeroRot = new Vector3(x, y, z);
  54. }
  55. }
  56. //sets current position as zero -> straighten handlebar and call this function
  57. public void Calibrate()
  58. {
  59. zeroRot = trackerTransform.localRotation.eulerAngles;
  60. zeroPos = trackerTransform.localPosition;
  61. PlayerPrefs.SetFloat(KeyRotX, zeroRot.x);
  62. PlayerPrefs.SetFloat(KeyRotY, zeroRot.y);
  63. PlayerPrefs.SetFloat(KeyRotZ, zeroRot.z);
  64. PlayerPrefs.SetFloat(KeyPosX, zeroPos.x);
  65. PlayerPrefs.SetFloat(KeyPosY, zeroPos.y);
  66. PlayerPrefs.SetFloat(KeyPosZ, zeroPos.z);
  67. PlayerPrefs.Save();
  68. }
  69. }
  70. }