How do I see if two rectangles intersect in JavaScript or pseudocode?

Discipol picture Discipol · Apr 15, 2013 · Viewed 11.9k times · Source

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.

Answer

ryanm picture ryanm · Apr 15, 2013

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 ||