• Advertisement
Sign in to follow this  

analysing intersecting rectangles

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

If you intended to correct an error in the post then please contact us.

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 this post


Link to post
Share on other sites
Advertisement
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/

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement