soshiki - 1 year ago 76

C++ Question

If I have two rectangles whose positions are deifned using two 2D vectors (i.e. top left, bottom right) how can I check for the points they are intersecting?

Answer Source

I assume you actually want the result of the intersection, not only the test if both rectangles intersect.

The intersection of rect1 = (l1, t1, r1, b1) and rect2 = (l2, t2, r2, b2) is again a rectangle:

```
rectIntersection = ( max(l1, l2), max(t1, t2), min(r1, r2), min(b1, b2) )
```

rectIntersection is of course empty if `left >= right || top >= bottom`

assuming a rectangle is left/top-inclusive and right/bottom-exclusive.

The rectangles intersect if

```
l1 < r2 && l2<r1 && t1<b2 && t2<t1
```