|
| 1 | +using System.Collections.Generic; |
| 2 | +using UnityEngine; |
| 3 | +using UnityEngine.EventSystems; |
| 4 | +using UnityEngine.UI; |
| 5 | + |
| 6 | +#nullable enable |
| 7 | +// ReSharper disable once CheckNamespace |
| 8 | + |
| 9 | +namespace GameLovers |
| 10 | +{ |
| 11 | + /// <summary> |
| 12 | + /// Extension methods for Unity objects. |
| 13 | + /// </summary> |
| 14 | + public static class UnityObjectsExtensions |
| 15 | + { |
| 16 | + /// <summary> |
| 17 | + /// Get the corners of the <see cref="RectTransform"/> in the local space of its Transform. |
| 18 | + /// </summary> |
| 19 | + public static Vector3[] GetLocalCornersArray(this RectTransform transform) |
| 20 | + { |
| 21 | + var corners = new Vector3[4]; |
| 22 | + var rect = transform.rect; |
| 23 | + var x = rect.x; |
| 24 | + var y = rect.y; |
| 25 | + var xMax = rect.xMax; |
| 26 | + var yMax = rect.yMax; |
| 27 | + |
| 28 | + corners[0] = new Vector3(x, y, 0f); |
| 29 | + corners[1] = new Vector3(x, yMax, 0f); |
| 30 | + corners[2] = new Vector3(xMax, yMax, 0f); |
| 31 | + corners[3] = new Vector3(xMax, y, 0f); |
| 32 | + |
| 33 | + return corners; |
| 34 | + } |
| 35 | + |
| 36 | + /// <summary> |
| 37 | + /// Get the corners of the <see cref="RectTransform"/> in world space of its Transform. |
| 38 | + /// </summary> |
| 39 | + public static Vector3[] GetWorldCornersArray(this RectTransform transform) |
| 40 | + { |
| 41 | + var corners = transform.GetLocalCornersArray(); |
| 42 | + var matrix4x = transform.localToWorldMatrix; |
| 43 | + for (int i = 0; i < 4; i++) |
| 44 | + { |
| 45 | + corners[i] = matrix4x.MultiplyPoint(corners[i]); |
| 46 | + } |
| 47 | + |
| 48 | + return corners; |
| 49 | + } |
| 50 | + |
| 51 | + /// <summary> |
| 52 | + /// Extension method for GraphicRaycaster that performs a raycast at the specified screen point. |
| 53 | + /// Returns true if any object was hit. |
| 54 | + /// </summary> |
| 55 | + public static bool RaycastPoint(this GraphicRaycaster raycaster, Vector2 screenPoint, out List<RaycastResult> results) |
| 56 | + { |
| 57 | + var eventData = new PointerEventData(EventSystem.current) |
| 58 | + { |
| 59 | + position = screenPoint, |
| 60 | + displayIndex = 0 |
| 61 | + }; |
| 62 | + |
| 63 | + results = new List<RaycastResult>(); |
| 64 | + |
| 65 | + raycaster.Raycast(eventData, results); |
| 66 | + |
| 67 | + return results.Count > 0; |
| 68 | + } |
| 69 | + } |
| 70 | +} |
0 commit comments