SFX_DistanceCollisionDetector.cs 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. using System;
  2. using UnityEngine;
  3. // ReSharper disable once CheckNamespace
  4. namespace QFX.SFX
  5. {
  6. public class SFX_DistanceCollisionDetector : SFX_ControlledObject, SFX_ICollisionsProvider
  7. {
  8. public bool IsSingleCollisionMode = true;
  9. public float CollisionDistance;
  10. public Vector3 TargetPosition;
  11. public DistanceComparisonMode DistanceMode;
  12. private bool _wasCollided;
  13. private Transform _transform;
  14. public event Action<SFX_CollisionPoint> OnCollision;
  15. private void Start()
  16. {
  17. _transform = transform;
  18. }
  19. private void LateUpdate()
  20. {
  21. if (!IsRunning)
  22. return;
  23. if (IsSingleCollisionMode && _wasCollided)
  24. return;
  25. bool wasCollided = false;
  26. Vector3 point = Vector3.zero;
  27. Vector3 normal = Vector3.zero;
  28. switch (DistanceMode)
  29. {
  30. case DistanceComparisonMode.Target:
  31. var distance = Vector3.Distance(_transform.position, TargetPosition);
  32. if (distance <= CollisionDistance)
  33. {
  34. wasCollided = true;
  35. point = TargetPosition;
  36. }
  37. break;
  38. case DistanceComparisonMode.Raycast:
  39. RaycastHit hit;
  40. if (Physics.Raycast(_transform.position, _transform.forward, out hit, CollisionDistance))
  41. {
  42. wasCollided = true;
  43. point = hit.point;
  44. normal = hit.normal;
  45. }
  46. break;
  47. }
  48. if (!wasCollided)
  49. return;
  50. if (!_wasCollided)
  51. _wasCollided = true;
  52. if (OnCollision != null)
  53. OnCollision.Invoke(new SFX_CollisionPoint
  54. {
  55. Point = point,
  56. Normal = normal
  57. });
  58. }
  59. public enum DistanceComparisonMode
  60. {
  61. Target,
  62. Raycast
  63. }
  64. }
  65. }