using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
public class CheckOverlap: MonoBehaviour
{
RectTransform rectTransform;
public RectTransform otherRect;
void Start ()
{
rectTransform = GetComponent<RectTransform> ();
}
void Update ()
{
if (otherRect.rect.Contains(rectTransform.rect.center))
{
print ("Contains");
}
if (otherRect.rect.Overlaps(rectTransform.rect))
{
print ("Overlaps");
}
}
}
…
…
This is the only code, and the two Rects I’m comparing are newly generated UI Images. One has the script and sets the other as “otherRect”.
It just spams “True” regardless of where the Rects are from scene start.
Like I was suspecting the RectTransform.rect
is in local space this means that the center will be always Vector3.zero. Try this fucntion:
Rect GetWorldSapceRect(RectTransform rt)
{
var r = rt.rect;
r.center = rt.TransformPoint(r.center);
r.size = rt.TransformVector(r.size);
return r;
}
Edit:
This code does not allow for any kind of rotation between the rectangles since it’s an axis aligned structure. To support that kind of thing you may want to use Physics2D to avoid any crazy maths.
Using Colliders2D inside your UI can be tricky but is doable.
The above answers didnt work for me using a world canvas though I found an easy work around. If all you need to check is whether the centre of one rect is within another this works fine. For it to work both transforms need to have the same parent as its local space based.
public class CheckRectTransformOverlap : MonoBehaviour
{
public bool rectIsWithin = false;
public RectTransform a;
public RectTransform b;
public Vector2 minMaxValuesX = new Vector2();
public Vector2 minMaxValuesY = new Vector2();
// Update is called once per frame
void LateUpdate()
{
rectIsWithin = RectContainsAnother1(a, b);
}
public bool RectContainsAnother1(RectTransform rct, RectTransform another)
{
minMaxValuesX.x = another.localPosition.x - (another.rect.width / 2);
minMaxValuesX.y = another.localPosition.x + (another.rect.width / 2);
minMaxValuesY.x = another.localPosition.y - (another.rect.height / 2);
minMaxValuesY.y = another.localPosition.y + (another.rect.height / 2);
if (rct.localPosition.x > minMaxValuesX.x & rct.localPosition.x < minMaxValuesX.y)
{
if (rct.localPosition.y > minMaxValuesY.x & rct.localPosition.y < minMaxValuesY.y)
{
return true;
}
else
{
return false;
}
}
else
{
return false;
}
}
}