# Problems with checking for rectangles that are touching

I am having trouble checking for rectangles that are touching each other.
I am not looking for a collider based solution.

I have two UI elements, and I would like to check if they are touching each other.

label1
X= 885.906, Y= -582.5767, Width= 60.5169, Height= 25

label2
X= 1007.376, Y= -570.8629, Width= 198.1284, Height= 25

Here is a picture of what they look like on the screen:

As you can see they are clearly touching each other.
I have tried a few things and nothing seems to return true(touching).

Here is the code:

First try:

``````public void TestOverlap()
{
if (labelB.GetRect().Overlaps(labelA.GetRect(), true))
{
Debug.Log("Overlaps");
}
else
{
Debug.Log("Doesn't Overlap");
}
}
``````

Second try:

``````public void TestOverlap()
{
if (Intersect(label1.GetRect(),label2.GetRect()))
{
Debug.Log("Overlaps");
}
else
{
Debug.Log("Doesn't Overlap");
}
}

public static bool Intersect(Rect a, Rect b)
{

bool c1 = a.xMin < b.xMax;
bool c2 = a.xMax > b.xMin;
bool c3 = a.yMin < b.yMax;
bool c4 = a.yMax > b.yMin;

return c1 & c2 & c3 & c4;
}
``````

Third try:

``````public void TestOverlap()
{
if (Intersect(label1.GetRect(),label2.GetRect()))
{
Debug.Log("Overlaps");
}
else
{
Debug.Log("Doesn't Overlap");
}
}

public static bool Intersect(Rect a, Rect b)
{
FlipNegative( ref a );
FlipNegative( ref b );

bool c1 = a.xMin < b.xMax;
bool c2 = a.xMax > b.xMin;
bool c3 = a.yMin < b.yMax;
bool c4 = a.yMax > b.yMin;

return c1 & c2 & c3 & c4;
}

public static void FlipNegative(ref Rect r)
{
if (r.width < 0)
r.x -= (r.width *= -1);

if (r.height < 0)
r.y -= (r.height *= -1);
}
``````

The GetRect function is producing the same numbers as indicated above.
Here is the GetRect function:

``````public Rect GetRect()
{
return new Rect(rectTransform.anchoredPosition.x, rectTransform.anchoredPosition.y, Width, Height);
}

public float Height
{
get
{
return rectTransform.rect.size.y * LocalScale.y;
}
}

public float Width
{
get
{
return rectTransform.rect.size.x * LocalScale.x;
}
}

public Vector2 LocalScale
{
get
{
return new Vector2(rectTransform.localScale.x, rectTransform.localScale.y);
}
}
``````

I got it working with this bit of code:

``````public bool Overlaps(Label_UI labelA, Label_UI labelB)
{
if (Math.Abs(labelA.Position.x - labelB.Position.x) < (Math.Abs(labelA.Width + labelB.Width) / 2) && (Math.Abs(labelA.Position.y - labelB.Position.y) < (Math.Abs(labelA.Height + labelB.Height) / 2)))
{
return true;
}

return false;
}
``````