# analysing intersecting rectangles

This topic is 4031 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

Hi, I'm looking for a way to determine the intersections between 2 rectangles of different sizes. The result of this function should be 3 collections of rectangles (in case of intersection of course) : - collection A : contains the rectangle shared by both original rectangles - collection B : a collection of rectangles describing all of the first rectangle that's not part of the intersection (using the least possible nr of rectangles) - collection C : a collection of rectangles describing all of the second rectangle that's not part of the intersection (using the least possible nr of rectangles) ex: http://iljanated.googlepages.com/intersection.JPG I think I can figure this out myself , but I suppose somebody must have already cracked his head over this one in the last 50 years of programming and come up with something faster/better looking than my attempts so far ... PS rectangles are defined by 2 ints (LEFT,TOP) and 2 ints (WIDTH,HEIGHT) or (RIGHT,BOTTOM)

##### Share on other sites
Dave Eberly's Geometric Tools has an intersection library. I believe that also includes the CSG (constructive solid geometry, which should return all the rectangles you need) stuff, but you might have to look around a bit.

##### Share on other sites
Here's what I would do.

First I'm going to assume that you have a SDL-like rectangle class. For the way that I'm doing this, it will be easier to use the top-left/lower-right corners.
(I'm writing this in C++; it should be pretty comprehensible.)

//Example of rectangle structure/class
struct RECT{
int x1,y1; //Coordinates of top-left corner
int x2,y2; //Coordinates of bottom-right corner
}

Assume that you have two rectangles:
RECT a,b;

First thing that you want to do is see which corners of rectangle b is within rectangle a.

//Is the top-left of b in a. Return true/false
bool tl = a.x1<b.x1 && b.x1<a.x2 && a.y1<b.y1 && b.y1<b.y2;

The rest follow this pattern. Change only the b. variables for each corner:

bool tr = a.x1<b.x2 && b.x2<a.x2 && a.y1<b.y1 && b.y1<b.y2;
bool bl = a.x1<b.x1 && b.x1<a.x2 && a.y1<b.y2 && b.y2<b.y2;
bool br = a.x1<b.x2 && b.x2<a.x2 && a.y1<b.y2 && b.y2<b.y2;

From here just check each case.
The rest of the code you should be able to figure out.

Hope it helps,
T.J. Gaffney
http://bringbackthelulz.com/

1. 1
2. 2
Rutin
18
3. 3
4. 4
5. 5

• 9
• 9
• 14
• 12
• 10
• ### Forum Statistics

• Total Topics
633271
• Total Posts
3011161
• ### Who's Online (See full list)

There are no registered users currently online

×