Lets say I’ve got two squares and I know their positions, a red and blue square:
redTopX;
redTopY;
redBotX;
redBotY;
blueTopX;
blueTopY;
blueBotX;
blueBotY;
Now, I want to check if square blue resides (partly) within (or around) square red. This can happen in a lot of situations, as you can see in this image I created to illustrate my situation better:
alt text http://www.feedpostal.com/etc/ranges.gif
Note that there’s always only one blue and one red square, I just added multiple so I didn’t have to redraw 18 times.
My original logic was simple, I’d check all corners of square blue and see if any of them are inside square red:
if (
((redTopX >= blueTopX) && (redTopY >= blueTopY) && (redTopX <= blueBotX) && (redTopY <= blueBotY)) || //top left
((redBotX >= blueTopX) && (redTopY >= blueTopY) && (redBotX <= blueBotX) && (redTopY <= blueBotY)) || //top right
((redTopX >= blueTopX) && (redBotY >= blueTopY) && (redTopX <= blueBotX) && (redBotY <= blueBotY)) || //bottom left
((redBotX >= blueTopX) && (redBotY >= blueTopY) && (redBotX <= blueBotX) && (redBotY <= blueBotY)) //bottom right
) {
//blue resides in red
}
Unfortunately, there are a couple of flaws in this logic. For example, what if red surrounds blue (like in situation 1)?
I thought this would be pretty easy but am having trouble coming up with a good way of covering all these situations.. can anyone help me out here?
Regards,
Tom
A test that checks whether red rectangle resides completely outside the blue rectangle looks as follows
Now, the negative of that will tell you whether red rectangle intersects the blue rectangle
If you wish, you can apply the De Morgan rule and rewrite it as
Of course, the above tests assume that the coordinates are “normalized*, i.e.
Also, the comparisons might be strict or non-strict depending on whether you consider touching rectangles as intersecting or not.
EDIT: I see that you use a different convention for rectangle coordinates:
Topis the lower coordinate andBotis the higher one, i.e.To handle this case you just need to swap the
BotandTopcoordinates in all conditions. For example, the last one will now look as follows