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

后端 未结 5 2107
孤城傲影
孤城傲影 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:32

    A look at the matter from a different site.

    The case turns out to be quite simple if we look at the problem (algorithm) from the other side.

    It means that instead of answering the question: "Are the rectangles overlap?", we will answer the question: "Are the rectangles do not overlap?".

    In the end, both questions resolve the same problem but the answer to the second question is simpler to implement because rectangles do not overlap only when one is under the other or when one is more to the left of the other (it is enough for one of these cases to take place, but of course it may happen that both will happen simultaneously - here a good understanding of the logical condition "or" is important). This reduces many cases that need to be considered on the first question.

    The whole matter is also simplified by the use of appropriate variable names:

    const areRectanglesOverlap = (rect1, rect2) => {
      let [left1, top1, right1, bottom1] = [rect1[0], rect1[1], rect1[2], rect1[3]],
          [left2, top2, right2, bottom2] = [rect2[0], rect2[1], rect2[2], rect2[3]];
      // The first rectangle is under the second or vice versa
      if (top1 < bottom2 || top2 < bottom1) {
        return false;
      }
      // The first rectangle is to the left of the second or vice versa
      if (right1 < left2 || right2 < left1) {
        return false;
      }
      // Rectangles overlap
      return true;
    }
    

    Even if we have a different representation of a rectangle, it is easy to adapt the above function to it by modifying only the section where the variables changes are defined. The further part of the function remains unchanged (of course, the comments are not really needed here, but I added them so that everyone could quickly understand this simple algorithm).

    An equivalent but maybe a little less readable form of the above function may look like this:

    const areRectanglesOverlap = (rect1, rect2) => {
    
      let [left1, top1, right1, bottom1] = [...rect1],
          [left2, top2, right2, bottom2] = [...rect2];
      
      return !(top1 < bottom2 || top2 < bottom1 || right1 < left2 || right2 < left1);
    }
    

提交回复
热议问题