Take the 2-minute tour ×
Mathematics Stack Exchange is a question and answer site for people studying math at any level and professionals in related fields. It's 100% free, no registration required.

I have 2 rectangles (black and blue), each of which are defined by 4 floating points values based on their location (left, top, right, bottom).

For example, a 25 x 25 rectangle might be defined as:

left = 400.0
right = 425.0
top = 300.0
bottom = 325.0f

The upper left corner of that rectangle would be located at:

(400.0, 300.0).

And the lower right corner of that rectangle would be located at:

(425.0, 325.0)

The first rectangle is black and does not move. The second rectangle is blue and is capable of moving. I would like to determine which side (top, left, right or bottom) of the black rectangle is hit by the blue rectangle.

For example, in this situation, I would like to know that the blue rectangle hit the black rectangle on its bottom side:

enter image description here

The initial way that I thought about figuring this out was taking the minimum of these calculations:

|blue top - black bottom|
|blue right - black left|
|blue bottom - black top|
|blue left - black right|

In the above example, it would be clear that I was hitting the bottom but consider a situation like this:

enter image description here

The blue rectangle is still hitting the bottom of the black rectangle but the value:

|blue right - black left|

may be less than or equal to:

|blue top - black bottom|

Is there a better way using simple math to determine which side of the black rectangle is hit?

share|improve this question
    
Consider projections into one dimention. Two rectangles are intersecting only if both their projections onto X and Y axes intersect (and you can calculate them using min and max functions). –  dtldarek Dec 16 '12 at 22:50

1 Answer 1

blue top is hit iff black bottom $\le$ blue top $\le$ black top and blue left $\le$ black right and black left $\le$ blue right.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.