FrontWheelTracker.cs 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. using System;
  2. using UnityEngine;
  3. namespace Tracking
  4. {
  5. public class FrontWheelTracker : MonoBehaviour
  6. {
  7. private const String KEY_POS_X = "vive_tracker_pos_x";
  8. private const String KEY_POS_Y = "vive_tracker_pos_y";
  9. private const String KEY_POS_Z = "vive_tracker_pos_z";
  10. private const String KEY_ROT_X = "vive_tracker_rot_x";
  11. private const String KEY_ROT_Y = "vive_tracker_rot_y";
  12. private const String KEY_ROT_Z = "vive_tracker_rot_z";
  13. private Transform trackerTransform;
  14. private Vector3 zeroRot;
  15. private Vector3 zeroPos;
  16. public Vector3 Rotation
  17. {
  18. get
  19. {
  20. var newVal = trackerTransform.localRotation.eulerAngles - zeroRot;
  21. var x = newVal.x;
  22. var y = newVal.y;
  23. var z = newVal.z;
  24. if (x > 180) x = -(360 - x);
  25. if (y > 180) y = -(360 - y);
  26. if (z > 180) z = -(360 - z);
  27. if (x < -180) x = -(-360 - x);
  28. if (y < -180) y = -(-360 - y);
  29. if (z < -180) z = -(-360 - z);
  30. return new Vector3(x,y,z);
  31. }
  32. }
  33. public Vector3 Position => trackerTransform.localPosition - zeroPos;
  34. public Vector3 ZeroRot => zeroRot;
  35. public Vector3 ZeroPos => zeroPos;
  36. // Start is called before the first frame update
  37. void Start()
  38. {
  39. trackerTransform = transform;
  40. if (PlayerPrefs.HasKey(KEY_POS_X) && PlayerPrefs.HasKey(KEY_POS_Y) && PlayerPrefs.HasKey(KEY_POS_Z))
  41. {
  42. var x = PlayerPrefs.GetFloat(KEY_POS_X);
  43. var y = PlayerPrefs.GetFloat(KEY_POS_Y);
  44. var z = PlayerPrefs.GetFloat(KEY_POS_Z);
  45. zeroPos = new Vector3(x, y, z);
  46. }
  47. if (PlayerPrefs.HasKey(KEY_ROT_X) && PlayerPrefs.HasKey(KEY_ROT_Y) && PlayerPrefs.HasKey(KEY_ROT_Z))
  48. {
  49. var x = PlayerPrefs.GetFloat(KEY_ROT_X);
  50. var y = PlayerPrefs.GetFloat(KEY_ROT_Y);
  51. var z = PlayerPrefs.GetFloat(KEY_ROT_Z);
  52. zeroRot = new Vector3(x, y, z);
  53. }
  54. }
  55. // Update is called once per frame
  56. void Update()
  57. {
  58. }
  59. //sets current position as zero -> straighten handlebar and call this function
  60. public void Calibrate()
  61. {
  62. zeroRot = trackerTransform.localRotation.eulerAngles;
  63. zeroPos = trackerTransform.localPosition;
  64. PlayerPrefs.SetFloat(KEY_ROT_X, zeroRot.x);
  65. PlayerPrefs.SetFloat(KEY_ROT_Y, zeroRot.y);
  66. PlayerPrefs.SetFloat(KEY_ROT_Z, zeroRot.z);
  67. PlayerPrefs.SetFloat(KEY_POS_X, zeroPos.x);
  68. PlayerPrefs.SetFloat(KEY_POS_Y, zeroPos.y);
  69. PlayerPrefs.SetFloat(KEY_POS_Z, zeroPos.z);
  70. PlayerPrefs.Save();
  71. }
  72. }
  73. }