I'm given two points per rectangle, the top left and bottom right (with the points for the two rectangles being denoted as bR1 and bR2, the top left points being denoted as tL1 and tL2, et cetera), and I want to find out if the two rectangles overlap. Right now my code is as follows:
if(!(bR1.y < tL2.y ||
tL1.y > bR2.y ||
bR1.x < tL2.x ||
tL1.x > bR2.x ) )
//if this combination of conditions are met, then the rectangles overlap at some point
//
{
System.out.println("overlap found");
}
else if (rectangle1.tL.equals(rectangle2.tL) &&
rectangle1.bR.equals(rectangle2.bR))
//if this combination of conditions are met, then the rectangles are perfectly on top of one another
{
System.out.println("rectangles completely overlap");
}
else if(bL1.x>bL2.x &&
bL1.y<bL2.y &&
tR1.x<tR2.x &&
tR1.y>tR2.y) //if rectangle1 is within rectangle2
{
System.out.println("one rectangle completely within another");
}
else if(bL1.x<bL2.x &&
bL1.y>bL2.y &&
tR1.x>tR2.x &&
tR1.y<tR2.y)//if rectangle2 is within rectangle1
{
System.out.println("one rectangle completely within another");
}
Based on my tests, my algorithm is finding too few overlaps. I am almost certain that the only issue with my algorithm is that it does not account for squares were only the edges or corners are touching. Is this the case? If it is, then how do I address the issue of only edges overlapping? (I can easily address the corners touching issue the same way I address the rectangles fitting perfectly on top of one another.)