- Home /
Rect.Contains not working
The documentation says:
void Update()
{
Rect rect = new Rect(0, 0, 150, 150);
if (rect.Contains(Input.mousePosition))
Debug.Log("Inside");
}
Seems legit & simple
Now my code:
The traget is recognized by OnPointerEnter event -> the pointer is in the rect for sure!
But:
Is that a bug!?
Answer by JojoIV · Jan 02, 2019 at 07:14 PM
Sometimes the RectTransform.rect is a bit confusing and not always what you would expect (my experience). It depends on the canvas mode what you should do (maybe you have to translate either the pointer position or the rect). It may help you if you debug output the rectangle position and size as well as the pointer position to find out if this is causing the issue.
Yes, as per the manual, the RectTransform rect is in the parent's local space - how far the corner is from the parent item. Print it out and you'll see. Converting to absolute canvas coords is a real pain. I think most people use GetWorldCorners. But I think the normal way is a GraphicsRayCaster and you won't need to check rects.
Thanks for the hint with GetWorldCorners. Led me to RectTransformUtility.RectangleContainsScreenPoint that makes the job!
Any mention in the documentation would be useful. It seems very $$anonymous$$imalist...
Right, Rect.Contains is an extremely simple and straight forward method. It works just like you would expect. If something doesn't work the way you expect it's because of wrong assumptions about your input data.
The RectTransform is part of the 2d and UI system of Unity. It works hand in hand with the EventSystem. A UI canvas could be in screen space or in worldspace. GUI space usually has it's origin at the top left while screen space generally has the origin at the bottom left. Input.mousePosition gives you the mouse position in screen space, not UI space or relative to a canvas.