Home > Backend Development > C++ > How Do You Determine if Two Rectangles Overlap?

How Do You Determine if Two Rectangles Overlap?

Mary-Kate Olsen
Release: 2024-12-23 04:08:25
Original
996 people have browsed it

How Do You Determine if Two Rectangles Overlap?

Determining Overlap Between Rectangles:

Your initial approach to determining overlap between rectangles appears to be based on a different algorithm than the one linked in the question. The provided algorithm uses a more straightforward comparison of rectangle coordinates, as shown below:

if (RectA.Left < RectB.Right && RectA.Right > RectB.Left &&
    RectA.Top > RectB.Bottom && RectA.Bottom < RectB.Top) 

 // Assuming Left, Right, Top and Bottom are the coordinates of the rectangles along the X and Y axis
Copy after login

In Cartesian coordinates, this condition can be expressed as:

if (RectA.X1 < RectB.X2 && RectA.X2 > RectB.X1 &&
    RectA.Y1 > RectB.Y2 && RectA.Y2 < RectB.Y1)
Copy after login

Proof by Contradiction:

This condition is based on the principle of proof by contradiction. If any one of the following conditions is true, then the rectangles cannot overlap:

  • RectA's left edge is to the right of RectB's right edge (RectA is completely to the right of RectB)
  • RectA's right edge is to the left of RectB's left edge (RectA is completely to the left of RectB)
  • RectA's top edge is below RectB's bottom edge (RectA is completely below RectB)
  • RectA's bottom edge is above RectB's top edge (RectA is completely above RectB)

Therefore, the condition for overlap is the opposite of these conditions:

  • RectA's left edge is to the left of RectB's right edge
  • RectA's right edge is to the right of RectB's left edge
  • RectA's top edge is above RectB's bottom edge
  • RectA's bottom edge is below RectB's top edge

Additional Notes:

  • This algorithm assumes that the rectangles are parallel to the X and Y axes.
  • To allow for overlaps of one pixel, change the < and > operators to <= and >= on the relevant boundaries.
  • The algorithm can be easily adjusted for different coordinate systems (e.g., if Y increases from top to bottom).
  • The above is the detailed content of How Do You Determine if Two Rectangles Overlap?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template