| | 1 | | using UnityEngine; |
| | 2 | |
|
| | 3 | | public static class RectTransformExtensions |
| | 4 | | { |
| | 5 | | public static int CountCornersVisibleFrom(this RectTransform rectTransform, RectTransform viewport) |
| | 6 | | { |
| 1 | 7 | | Vector3[] viewCorners = new Vector3[4]; |
| 1 | 8 | | viewport.GetWorldCorners(viewCorners); |
| | 9 | |
|
| 1 | 10 | | Vector2 size = new Vector2(viewport.rect.size.x * viewport.lossyScale.x, viewport.rect.size.y * viewport.lossySc |
| 1 | 11 | | Rect screenBounds = new Rect(viewCorners[0], size); // Screen space bounds (assumes camera renders across the en |
| | 12 | |
|
| 1 | 13 | | Vector3[] objectCorners = new Vector3[4]; |
| 1 | 14 | | rectTransform.GetWorldCorners(objectCorners); |
| | 15 | |
|
| 1 | 16 | | int visibleCorners = 0; |
| | 17 | |
|
| 10 | 18 | | for (var i = 0; i < viewCorners.Length; i++) |
| | 19 | | { |
| 4 | 20 | | if (i != viewCorners.Length - 1) |
| 3 | 21 | | Debug.DrawLine(viewCorners[i], viewCorners[i + 1], Color.blue, 1.0f); |
| | 22 | | } |
| | 23 | |
|
| 10 | 24 | | for (var i = 0; i < objectCorners.Length; i++) // For each corner in rectTransform |
| | 25 | | { |
| 4 | 26 | | if (screenBounds.Contains(objectCorners[i])) // If the corner is inside the screen |
| | 27 | | { |
| 0 | 28 | | visibleCorners++; |
| | 29 | | } |
| | 30 | | } |
| | 31 | |
|
| 10 | 32 | | for (var i = 0; i < objectCorners.Length; i++) // For each corner in rectTransform |
| | 33 | | { |
| 4 | 34 | | if (i != objectCorners.Length - 1) |
| 3 | 35 | | Debug.DrawLine(objectCorners[i], objectCorners[i + 1], visibleCorners > 0 ? Color.green : Color.red, 1.0 |
| | 36 | | } |
| | 37 | |
|
| 1 | 38 | | return visibleCorners; |
| | 39 | | } |
| | 40 | | } |