- Home /
How can I detect if UI elements are overlapping without colliders?
Hello,
I want to detect if two or more UI elements are overlapping each other. I tried this with box colliders2D and rigidbody2D but on runtime when I access my menu I set the timescale to 0, so colliders didn't work, realized after I finished all my work :'(.
I also tried Rect.Overlap() and for test purpose I set a variable to true if two rect are overlapping, but I always get true back and never false.
Then I found this: https://developer.mozilla.org/en-US/docs/Games/Techniques/2D_collision_detection and tried to make it work, but same result as the Rect.Overlap(). Here is my code:
public class Rect_Test : MonoBehaviour
{
public GameObject image2;
Rect image1rect;
Rect image2rect;
public bool col;
// Start is called before the first frame update
void Start()
{
image1rect = transform.GetComponent<RectTransform>().rect;
image2rect = image2.transform.GetComponent<RectTransform>().rect;
}
// Update is called once per frame
void Update()
{
if (image1rect.x < image2rect.x + image2rect.width &&
image1rect.x + image1rect.width > image2rect.x &&
image1rect.y < image2rect.y + image2rect.height &&
image1rect.y + image1rect.height > image2rect.y)
{
col = true;
}
else
{
col = false;
}
}
}
Can someone explain me what I did wrong? Is this the best solution to detect "collision" of UI or should I use Raycast for it? My Canvas is set to Render Mode: Screen Space - Overlay and UI Scale Mode: Scale with Screen Size if that matters.
Answer by logicandchaos · Jan 12, 2021 at 12:37 PM
You can check the numbers, do the math. Write a simple bounding box algorithm, or use distance function.