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

后端 未结 5 2169
孤城傲影
孤城傲影 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条回答
  •  被撕碎了的回忆
    2021-02-19 05:43

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

提交回复
热议问题