Search Unity

Resolved How to clip a rect to screen bounds?

Discussion in 'Scripting' started by Meaningless-Trinket, Dec 6, 2022.

  1. Meaningless-Trinket

    Meaningless-Trinket

    Joined:
    Apr 25, 2020
    Posts:
    83
    Is it possible to clip a rect to the screen so when part of the rect goes off screen a new rect is made that is on screen?

    I was thinking about two screen space lines, one for xMin to xMax and one for yMin and yMax.

    The screen space lines are used to make new points if they go off screen?

    I don't know how to clip a rect to the screen so it is only on screen.
     
  2. jvo3dc

    jvo3dc

    Joined:
    Oct 11, 2013
    Posts:
    1,520
    It's actually pretty typical that there is no Intersection method in Rect. You could add it using an extension:
    Code (csharp):
    1.  
    2. public static class RectIntersection
    3. {
    4.    public static Rect? Intersection(this Rect rect1, Rect rect2)
    5.    {
    6.       if (!rect1.Overlaps(rect2)) return null;
    7.       float xMin = Mathf.Max(rect1.xMin, rect2.xMin);
    8.       float yMin = Mathf.Max(rect1.yMin, rect2.yMin);
    9.       float xMax = Mathf.Min(rect1.xMax, rect2.xMax);
    10.       float yMax = Mathf.Min(rect1.yMax, rect2.yMax);
    11.       return Rect.MinMaxRect(xMin, yMin, xMax, yMax);
    12.    }
    13. }
    14.  
    Then having your rect and the screen rect, you can do:
    Code (csharp):
    1.  
    2. Rect? clipped = rect.Intersection(screen);
    3.  
    Note that the result can also be null, for examply if your rect is fully outside the screen.
     
  3. Meaningless-Trinket

    Meaningless-Trinket

    Joined:
    Apr 25, 2020
    Posts:
    83
    Thank you, I will try this.

    I didn't know about intersecting rects.