views:

151

answers:

2

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.

A: 

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
A: 

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 maybe be simplified.

An perhaps you could take a look at this SO question as well:

http://stackoverflow.com/questions/115426/algorithm-to-detect-intersection-of-two-rectangles

ereOn