NearInteractionTouchableUnityUI.cs 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using UnityEngine;
  7. namespace SC.XR.Unity.Module_InputSystem {
  8. /// <summary>
  9. /// Use a Unity UI RectTransform as touchable surface.
  10. /// </summary>
  11. [RequireComponent(typeof(RectTransform))]
  12. public class NearInteractionTouchableUnityUI : BaseNearInteractionTouchable {
  13. private Lazy<RectTransform> rectTransform;
  14. public static IReadOnlyList<NearInteractionTouchableUnityUI> Instances => instances;
  15. private static readonly List<NearInteractionTouchableUnityUI> instances = new List<NearInteractionTouchableUnityUI>();
  16. public NearInteractionTouchableUnityUI() {
  17. rectTransform = new Lazy<RectTransform>(GetComponent<RectTransform>);
  18. }
  19. public override float DistanceToTouchable(Vector3 samplePoint, out Vector3 normal) {
  20. normal = Normal;
  21. Vector3 localPoint = transform.InverseTransformPoint(samplePoint);
  22. // touchables currently can only be touched within the bounds of the rectangle.
  23. // We return infinity to ensure that any point outside the bounds does not get touched.
  24. if(!rectTransform.Value.rect.Contains(localPoint)) {
  25. return float.PositiveInfinity;
  26. }
  27. // Scale back to 3D space
  28. localPoint = TransformSize(transform,localPoint);
  29. return Math.Abs(localPoint.z);
  30. }
  31. /// <summary>
  32. /// Transforms the size from local to world.
  33. /// </summary>
  34. /// <param name="transform">The transform.</param>
  35. /// <param name="localSize">The local size.</param>
  36. /// <returns>World size.</returns>
  37. public Vector3 TransformSize(Transform transform, Vector3 localSize) {
  38. Vector3 transformedSize = new Vector3(localSize.x, localSize.y, localSize.z);
  39. Transform t = transform;
  40. do {
  41. transformedSize.x *= t.localScale.x;
  42. transformedSize.y *= t.localScale.y;
  43. transformedSize.z *= t.localScale.z;
  44. t = t.parent;
  45. }
  46. while(t != null);
  47. return transformedSize;
  48. }
  49. protected void OnEnable() {
  50. instances.Add(this);
  51. }
  52. protected void OnDisable() {
  53. instances.Remove(this);
  54. }
  55. }
  56. }