How to find if two given rectangles overlap?

There are times when one may find themselves faced with two rectangles and be left wondering whether or not they are overlapping. In order to find out whether or not the two given rectangles overlap, the first step is to identify the rectangles. To do so, is to identify the coordinates of the rectangles. For this purpose, let’s consider them to be:

  • l1: Top Left coordinate of first rectangle
  • r1: Bottom Right coordinate of first rectangle
  • l2: Top Left coordinate of second rectangle
  • r2: Bottom Right coordinate of second rectangle

Then, lets write a function that would return true if the two given rectangles overlap: bool doOverlap(l1, r1, l2, r2)

The function should return true of one of the following conditions are met:

  • When left edge of R1 is on the right of R2's right edge. (That is, R1 is completely on the right of R2).
  • When right edge of R1 is on the left of R2's left edge. (That is, R1 is completely on the left of R2).
  • When top edge of R1 is on bottom of R2's bottom edge (That is, R1 is completely under R2).
  • When bottom edge of R1 is on top of R2's top edge (That is, R1 is completely over R2).

The function should return false for one of the following conditions:

  • One rectangle is above top edge of other rectangle.
  • One rectangle is on left side of left edge of other rectangle.

Add new comment

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.