CircleProximityField.cs 1.1 KB

1234567891011121314151617181920212223242526272829303132333435
  1. using UnityEngine;
  2. using UnityEngine.Assertions;
  3. namespace Rokid.UXR.Interaction {
  4. public class CircleProximityField : MonoBehaviour, IProximityField
  5. {
  6. [SerializeField]
  7. private Transform _transform;
  8. [SerializeField]
  9. private float _radius = 0.1f;
  10. protected virtual void Start()
  11. {
  12. Assert.IsNotNull(_transform);
  13. }
  14. // Closest point to circle is computed by projecting point to the plane
  15. // the circle is on and then clamping to the circle
  16. public Vector3 ComputeClosestPoint(Vector3 point)
  17. {
  18. Vector3 vectorFromPlane = point - _transform.position;
  19. Vector3 planeNormal = -1.0f * _transform.forward;
  20. Vector3 projectedPoint = Vector3.ProjectOnPlane(vectorFromPlane, planeNormal);
  21. float distanceFromCenterSqr = projectedPoint.sqrMagnitude;
  22. float worldRadius = transform.lossyScale.x * _radius;
  23. if (distanceFromCenterSqr > worldRadius * worldRadius)
  24. {
  25. projectedPoint = worldRadius * projectedPoint.normalized;
  26. }
  27. return projectedPoint + _transform.position;
  28. }
  29. }
  30. }