Monday, May 13, 2024
 Popular · Latest · Hot · Upcoming
4
rated 0 times [  5] [ 1]  / answers: 1 / hits: 19518  / 11 Years ago, sun, april 14, 2013, 12:00:00

I have two rectangles which I must return in a function whether they intersect or not.



They are represented by [ x0, y0, x1, y1 ] pairs that represent the top-left and bottom-right corner of the rectangles. Alternatively, your solution could be [ x0, y0, width, height ] if its somehow simpler, I can adapt my function's parameter input by it.



I tried to see if any of the two corners from rectangle A are included in rectangle B but if A is larger than B and B is partially included in A, it will say it doesn't overlap. Now I could try A and B but this seems to be a bad way to do things.



I can't premake a big grid and occupy cells by the rectangles because it is unknown what rectangles come as. All I can tell is that they are unsigned integers, min 0 and with an unknown max.


More From » geometry

 Answers
3

Check for the cases where the rectangles are definitely not intersecting. If none of these cases are true then the rectangles must intersect. i.e.:



public boolean rectanglesIntersect( 
float minAx, float minAy, float maxAx, float maxAy,
float minBx, float minBy, float maxBx, float maxBy ) {
boolean aLeftOfB = maxAx < minBx;
boolean aRightOfB = minAx > maxBx;
boolean aAboveB = minAy > maxBy;
boolean aBelowB = maxAy < minBy;

return !( aLeftOfB || aRightOfB || aAboveB || aBelowB );
}


This illustrates the concept but could be made slightly faster by inlining the booleans so as to take advantage of the short-circuiting behavior of ||


[#78911] Saturday, April 13, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
billie

Total Points: 101
Total Questions: 114
Total Answers: 98

Location: Burundi
Member since Wed, Nov 25, 2020
4 Years ago
;