3

Moving ahead from previous question.I have two rectangle and they look like this:

struct Rect
{
 NSPoint topLeft; 
 NSPoint topRight; 
 NSPoint bottomLeft; 
 NSPoint bottomRight; 
}

I use something similar code to check whether rectangles intersects(or collision) . In case If 2 rectangles intersects I want to calculate the area of intersection in the first rectangle or the points where the second rectangle intersects with first rectangle (i.e. intersection coordinates).

How do I calculate the intersecting points or the area of intersection.

Community
  • 1
  • 1
Raviprakash
  • 2,410
  • 6
  • 34
  • 56

2 Answers2

2

You can determine the points of intersection by doing this:

foreach line in rectangle 1: line1
  foreach line in rectangle 2: line2
    find point of intersection for line1, line2

to find the intersection point of two lines:

http://local.wasp.uwa.edu.au/~pbourke/geometry/lineline2d/

You can find the area of intersection by finding the points of intersection, and splitting the lines based off that to create new sides/delete sides. You could get up to 8 points in the resulting polygon, or as few as 3 (not counting degenerate cases).

No, I didn't say this is the most efficient method, but it will work :)

Merlyn Morgan-Graham
  • 58,163
  • 16
  • 128
  • 183
  • In case that article goes down, here are a couple more articles: http://en.wikipedia.org/wiki/Line_segment_intersection and http://en.wikipedia.org/wiki/Line-line_intersection. I'd put the equations here but the common line-line intersection solver equations are kind of a mess, and won't help to explain the higher level algorithm. They're fairly easy to derive by hand anyhow. Plus you might want to try sweep algorithms since you're dealing with several lines at ones. – Merlyn Morgan-Graham Oct 15 '11 at 22:51
2

What you are asking seems to be a specific case of "polygon intersection". (since rectangles are polygons).

Here is a library that does this:

http://www.cs.man.ac.uk/aig/staff/alan/software/

Maybe it can help (they somehow talk about the algorithm). However, if you only need rectangle intersection, it can probably be simplified.

Also, perhaps you could take a look at this SO question:

Algorithm to detect intersection of two rectangles?

Community
  • 1
  • 1
ereOn
  • 53,676
  • 39
  • 161
  • 238