CustomWheelColliderSlopeAdjustment.cs 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using UnityEngine;
  5. public class CustomWheelColliderSlopeAdjustment : MonoBehaviour
  6. {
  7. public CustomWheelCollider frontWheel;
  8. public CustomWheelCollider rearWheel;
  9. public Transform rotatePoint;
  10. public float timeDifferenceTolerance = 0.0001f;
  11. public Vector3 dif; //TODO: remove
  12. private Transform t;
  13. private bool isHitting = false;
  14. private float angle = 0f;
  15. private void OnGUI()
  16. {
  17. GUI.TextField(new Rect(Screen.width - 200, 10, 190, 80), $"Hitting? {isHitting}\nAngle: {angle:n2}\nrw: {rearWheel.CurrentHit?.Hit.point}\nfw: {frontWheel.CurrentHit?.Hit.point}");
  18. }
  19. private void Start()
  20. {
  21. t = transform;
  22. }
  23. private void FixedUpdate()
  24. {
  25. isHitting = false;
  26. if (frontWheel.CurrentHitNumber > 1)
  27. {
  28. angle = -.5f;
  29. Rotate();
  30. return;
  31. }
  32. if (rearWheel.CurrentHitNumber > 1)
  33. {
  34. angle = .5f;
  35. Rotate();
  36. return;
  37. }
  38. //TODO: this is probably called almost never
  39. if (frontWheel.CurrentHit == null || rearWheel.CurrentHit == null) return;
  40. var fwHit = frontWheel.CurrentHit.Value;
  41. var rwHit = rearWheel.CurrentHit.Value;
  42. if (fwHit.Timestamp - rwHit.Timestamp <= timeDifferenceTolerance)
  43. {
  44. UpdateTransformRotation(fwHit, rwHit);
  45. }
  46. }
  47. private void UpdateTransformRotation(HitInfo fwHit, HitInfo rwHit)
  48. {
  49. isHitting = true;
  50. dif = t.TransformPoint(fwHit.Hit.point) - t.TransformPoint(rwHit.Hit.point);
  51. angle = -Mathf.Atan(dif.y / dif.z) * Mathf.Rad2Deg; //TODO: is it that easy?
  52. Debug.DrawLine(rwHit.Hit.point, rwHit.Hit.point + t.right, Color.red);
  53. Rotate();
  54. //t.RotateAround(rotatePoint.position, t.right, angle) ;
  55. //t.localRotation = Quaternion.Euler(t.localRotation.eulerAngles + Vector3.right * angle);
  56. }
  57. private void Rotate()
  58. {
  59. t.RotateAround(rotatePoint.position, t.right, angle) ;
  60. angle = 0f;
  61. }
  62. }