Beispiel #1
0
    /// <summary>
    /// Counts the bounding box corners of the given RectTransform that are visible from the given Camera in screen space.
    /// </summary>
    /// <returns>The amount of bounding box corners that are visible from the Camera.</returns>
    /// <param name="rectTransform">Rect transform.</param>
    /// <param name="camera">Camera.</param>
    private static int CountCornersVisibleFrom(this RectTransform rectTransform, Camera camera, CanvasScaler cs)
    {
        Vector2 scaled       = cs.Scale((new Vector2(Screen.width, Screen.height)));
        Rect    screenBounds = new Rect(0f, 0f, scaled.x, scaled.y); // Screen space bounds (assumes camera renders across the entire screen)

        Vector3[] objectCorners = new Vector3[4];
        rectTransform.GetWorldCorners(objectCorners);

        int     visibleCorners = 0;
        Vector3 tempScreenSpaceCorner;                        // Cached

        for (var i = 0; i < objectCorners.Length; i++)        // For each corner in rectTransform
        {
            tempScreenSpaceCorner = objectCorners[i];         // Transform world space position of corner to screen space
            if (screenBounds.Contains(tempScreenSpaceCorner)) // If the corner is inside the screen
            {
                visibleCorners++;
            }
        }
        return(visibleCorners);
    }