Determine whether two rectangles intersect (Rect Intersection)

0x00 Preface

Recently, in the process of developing a 2D configuration graphics component, the math module inside involves the judgment of whether two rectangles intersect.

This problem was written many years ago, it is a small algorithm.

Search on the Internet, there are many ideas, and some ideas need to be judged based on multiple combinations, which is more complicated. For example, the situation where two rectangles intersect may have the following types:

image.png

Each type has multiple subtypes.

0x01 Body

In fact, you can think about this problem in reverse, which is relatively simple. What are the cases where the two rectangles A and B do not intersect, and then negate them through bool, which is the case of intersecting.
Suppose a rectangle is defined as follows:

class Rect {
    constructor(x,y,w,h) {
      this.x = x;
      this.y = y;
      this.w = w;
      this.h = h;
      
      this.r = x + w; // r表示矩形的右边
      this.b = y + h; // b 表示矩形的下边
    }
}

Disjoint cases can be summarized into the following cases:

  • A is to the left of B (Ar < Bx)
  • A is to the right of B ( Br < Ax)
  • A is on top of B (Ab < By )
  • A is below B (Bb < Ay)

So the disjoint code is as follows:

A.r < B.x || B.r < A.x || A.b < B.y || B.b <A.y

In this case, the inversion is the case of intersection:

!(A.r < B.x || B.r < A.x || A.b < B.y || B.b <A.y)

After negation or change with:

A.r >= B.x && B.r >= A.x && A.b >= B.y && B.b >= A.y

Try to ask ChatGPT, it gives exactly this kind of thinking, as shown below:

image.png

0x02 Conclusion

  • Sometimes it's a good way to think about problems in reverse
  • ChatGPT is awesome.

0x03 The Last

Finally, follow the official account "ITMan Biaoshu" to add the author's WeChat to communicate and receive more valuable articles in time.

Guess you like

Origin blog.csdn.net/netcy/article/details/131104998