I need to do this for two reasons : I want to make a draggable UI window but prevent it from being dragged outside the screen, and I also want to make sure my tooltips don’t overflow from the screen and get cut.
How should I go about doing that ? Is there a way maybe to get the size of a UI element and the size of the Canvas and then compare them ? I feel like I’m missing something here.
I use Canvas in Screen Space - Overlay option.
To detect if a RectTransform is visible or out of the screen in my projects I use this solution:
void Update ()
{
Vector3[] v = new Vector3[4];
GetComponent<RectTransform>().GetWorldCorners (v);
float maxY = Mathf.Max (v [0].y, v [1].y, v [2].y, v [3].y);
float minY = Mathf.Min (v [0].y, v [1].y, v [2].y, v [3].y);
//No need to check horizontal visibility: there is only a vertical scroll rect
//float maxX = Mathf.Max (v [0].x, v [1].x, v [2].x, v [3].x);
//float minX = Mathf.Min (v [0].x, v [1].x, v [2].x, v [3].x);
if (maxY < 0 || minY > Screen.height) {
// Do Something that disable UI elements
} else {
// Do something that re-enable UI elements
}
}
My solution is based on the above so credits due. This works with a canvas set as Screen space Camera.
Use this to create a test rect the size of the screen in some Awake fn using the canvas you want to test against:
Vector3 c1 = mainCanvas.worldCamera.ScreenToWorldPoint(Vector3.zero);
Vector3 c2 = mainCanvas.worldCamera.ScreenToWorldPoint(new Vector3(Screen.width, Screen.height));
Rect canvasRect = new Rect( c1, new Vector2(c2.x-c1.x, c2.y-c1.y));
Then I did tests on the UI element like this:
Vector3[] corners = new Vector3[4];
GetComponent<RectTransform>().GetWorldCorners(corners);
Rect rec = new Rect(corners[0].x, corners[0].y, corners[2].x-corners[0].x, corners[2].y-corners[0].y);
if (rec.Overlaps(canvasRect))
...
This makes sense to me (in a way) but I am finding that where the objectCorners are in world coordinates my container rect are different so the test always fails?
This makes sense to me (in a way) but I am finding that where the objectCorners are in world coordinates my container rect are different so the test always fails?