CustomWheelCollider.cs 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. using System.Linq;
  2. using UnityEngine;
  3. public struct HitInfo
  4. {
  5. public readonly RaycastHit Hit;
  6. public readonly float Timestamp;
  7. public HitInfo(float timestamp, RaycastHit hit)
  8. {
  9. Timestamp = timestamp;
  10. Hit = hit;
  11. }
  12. }
  13. public class CustomWheelCollider : MonoBehaviour
  14. {
  15. public float radius;
  16. public int numberOfRays;
  17. public int collisionLayer = 11;
  18. private Vector3[] rayDirections;
  19. //[Range(10f,90f)]
  20. //public float maxDetectableAngle = 45f;
  21. private Transform t;
  22. public HitInfo? CurrentHit { private set; get; }
  23. public int CurrentHitNumber { private set; get; }
  24. private void Start()
  25. {
  26. t = transform;
  27. rayDirections = CalculateRayDirections();
  28. }
  29. private void FixedUpdate()
  30. {
  31. var results = new HitInfo?[numberOfRays];
  32. for (var i = 0; i < numberOfRays; i++) results[i] = CastRay(i);
  33. CurrentHit = results.FirstOrDefault(r => r != null);
  34. CurrentHitNumber = results.Count(r => r != null);
  35. }
  36. public Vector3[] CalculateRayDirections()
  37. {
  38. //var startAngle = 90f - maxDetectableAngle;
  39. //var stopAngle = 90f + maxDetectableAngle;
  40. var anglePerRot = 360f / numberOfRays;
  41. var directions = new Vector3[numberOfRays];
  42. for (var i = 0; i < numberOfRays; i++) directions[i] = CalculateRayDirection(i * anglePerRot * Mathf.Deg2Rad);
  43. return directions;
  44. }
  45. private Vector3 CalculateRayDirection(float angle)
  46. {
  47. //(1,0,0) rotated by angle
  48. var x = 1f;
  49. var y = 0f;
  50. return new Vector3(0, Mathf.Sin(angle) * x + Mathf.Cos(angle) * y, Mathf.Cos(angle) * x - Mathf.Sin(angle) * y);
  51. }
  52. /*private Vector3 RotateOnYZAxis(Vector3 vector, float angle)
  53. {
  54. var y = vector.y;
  55. var z = vector.z;
  56. return new Vector3(0, Mathf.Sin(angle) * y + Mathf.Cos(angle) * z, Mathf.Cos(angle) * y - Mathf.Sin(angle) * z);
  57. }*/
  58. private HitInfo? CastRay(int index)
  59. {
  60. var direction = t.TransformDirection(rayDirections[index]);
  61. var layerMask = 1 << collisionLayer;
  62. RaycastHit hit;
  63. //var direction = t.forward;
  64. //direction = new Vector3(direction.x, direction.z * Mathf.Sin(angle) + direction.y * Mathf.Cos(angle),
  65. // direction.z * Mathf.Cos(angle) - direction.y * Mathf.Sin(angle));
  66. if (Physics.Raycast(t.position, direction, out hit, radius, layerMask))
  67. {
  68. Debug.DrawRay(t.position, direction * hit.distance, Color.yellow);
  69. //Debug.Log("Did Hit: ");
  70. return new HitInfo(Time.fixedTime, hit);
  71. }
  72. Debug.DrawRay(t.position, direction * radius, Color.white);
  73. return null;
  74. }
  75. }