Given two rectangles (as shown in the following figure), , are lower-left points while and are top-right points. We want to find out whether these two rectangles overlap each other.
The solution is simple: instead of checking the situations these two collide, we can check the opposite. There are four situations that these two rectangles do not overlap each other.
- P2x > P1x
- P3x < P0x
- P2y > P1y
- P3y < P0y
They check the following respectively.
- The blue box is on the right of the red box.
- The blue box is on the left of the red box.
- The blue box is on the top of the red box.
- The blue box is on the bottom of the red box.
The boolean NOT should give the correct test on whether these two collide. The following Delphi code tests for box intersection algorithm.
// type definition type _2DP = array [1 .. 2] of Single; function v2DPIntersect( const lowerleft0: _2DP; const topright0: _2DP; const lowerleft1: _2DP; const topright1: _2DP ): boolean; inline; begin Result := (not ((topright1[1] < lowerleft0[1]) or (lowerleft1[1] > topright0[1]) or (topright1[2] < lowerleft0[2]) or (lowerleft1[2] > topright0[2]))); end;
Based on this, we can futher compute the intesection area (rectangle). The following four coordinates are computed.
The intersection area is thus represented by (lower-left to upper-right rectangle) (x0, y0) ~ (x1, y1).
You may refer to this post: Two Rectangles Overlap Detection Algorithm in C++ if you want to perform the overlapping tests for two rectangles.
–EOF (The Ultimate Computing & Technology Blog) —
loading...
Last Post: Remainder Computation (Modulo) on Floating Numbers, Delphi and Python
Next Post: Disable Buggy Compiler Warnings Undefined Function Return for Delphi 2007