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

后端 未结 5 2165
孤城傲影
孤城傲影 2021-02-19 04:53

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 t

5条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-19 05:31

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

提交回复
热议问题