0 0 0 0


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 unknown max.

Best Answer:

Two rectangles are overlapping if both the x and the y areas Overlap. If any of the x co-ordinates overlap the other rectangles, then there will be an over lap.

Along the x axis, either the first point is within the other two rectangles, the second point is within the other two, or two points are on opposite sides of the other points.

function checkRectOverlap(rect1, rect2) {
     * Each array in parameter is one rectangle
     * in each array, there is an array showing the co-ordinates of two opposite corners of the rectangle
     * Example:
     * [[x1, y1], [x2, y2]], [[x3, y3], [x4, y4]]
    //Check whether there is an x overlap
    if ((rect1[0][0] < rect2[0][0] && rect2[0][0] < rect1[1][0]) //Event that x3 is inbetween x1 and x2
        || (rect1[0][0] < rect2[1][0] && rect2[1][0] < rect1[1][0]) //Event that x4 is inbetween x1 and x2
        || (rect2[0][0] < rect1[0][0] && rect1[1][0] < rect2[1][0])) {  //Event that x1 and x2 are inbetween x3 and x4
        //Check whether there is a y overlap using the same procedure
        if ((rect1[0][1] < rect2[0][1] && rect2[0][1] < rect1[1][1]) //Event that y3 is between y1 and y2
            || (rect1[0][1] < rect2[1][1] && rect2[1][1] < rect1[1][1]) //Event that y4 is between y1 and y2
            || (rect2[0][1] < rect1[0][1] && rect1[1][1] < rect2[1][1])) { //Event that y1 and y2 are between y3 and y4
            return true;
    return false;

Copyright © 2011 Dowemo All rights reserved.    Creative Commons   AboutUs