How to detect if a certain range resides (partly) within an other range?

Posted by Tom on Stack Overflow See other posts from Stack Overflow or by Tom
Published on 2010-05-28T16:28:09Z Indexed on 2010/05/28 16:32 UTC
Read the original article Hit count: 194

Filed under:
|
|
|

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

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

© Stack Overflow or respective owner

Related posts about algorithm

Related posts about math