1
0

FrontWheelTracker.cs 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using UnityEditor;
  5. using UnityEngine;
  6. namespace Tracking
  7. {
  8. public class FrontWheelTracker : CalibratableTracker
  9. {
  10. protected override string KeyPrefix => "fw";
  11. public float trackerDistanceToWheelCenterPoint;
  12. public KineticLegTracker legTracker;
  13. public int framesToConsider = 10;
  14. public bool useTrackerRotationInsteadOfPosition;
  15. public float SteerRotation => framesToConsider > 1
  16. ? CalculateSteerRotationMultiFrame()
  17. : CalculateSteerRotationSingleFrame();
  18. public Vector3 DebugPosOnBikePlane { private set; get; }
  19. private Queue<float> previousValues;
  20. private void OnEnable()
  21. {
  22. if (framesToConsider > 1)
  23. {
  24. previousValues = new Queue<float>(framesToConsider);
  25. }
  26. }
  27. private float CalculateSteerRotationSingleFrame()
  28. {
  29. if (useTrackerRotationInsteadOfPosition) return RelativeRotation.y;
  30. var posOnBikePlane = GetPosOnBikePlane();
  31. return TrackerPositionToAngle(posOnBikePlane);
  32. }
  33. private float CalculateSteerRotationMultiFrame()
  34. {
  35. var angleThisFrame = CalculateSteerRotationSingleFrame();
  36. if (previousValues.Count > framesToConsider)
  37. {
  38. previousValues.Dequeue();
  39. }
  40. previousValues.Enqueue(angleThisFrame);
  41. //easiest way -> avg; TODO maybe in future, remove outliers
  42. return previousValues.Average();
  43. }
  44. private Vector3 GetPosOnBikePlane()
  45. {
  46. //legTracker position is added to compensate movements of the whole installation
  47. Vector3 legTrackerPos = Vector3.zero;
  48. if (legTracker.isActiveAndEnabled)
  49. {
  50. legTrackerPos = legTracker.RelativePosition;
  51. }
  52. var posOnBikePlane = Vector3.ProjectOnPlane(RelativePosition + legTrackerPos, bicycleTransform.up);
  53. DebugPosOnBikePlane = posOnBikePlane;
  54. /*if (Mathf.Abs(posOnBikePlane.x / trackerDistanceToWheelCenterPoint) >= 1f)
  55. {
  56. Debug.LogError("Strange behaviour!");
  57. //EditorApplication.isPaused = true;
  58. }*/
  59. return posOnBikePlane;
  60. }
  61. private float TrackerPositionToAngle(Vector3 posOnBikePlane)
  62. {
  63. var theta = Mathf.Acos(Mathf.Clamp(posOnBikePlane.x / trackerDistanceToWheelCenterPoint, -1f, 1f));
  64. return 90f - theta * Mathf.Rad2Deg;
  65. }
  66. }
  67. }