views:

1100

answers:

2

Edit:

Simple code I used to solve the problem in case anyone is interested (thanks to Fredrik):

    int windowOverlap(Rectangle rect1, Rectangle rect2)
    {
        if (rect1.IntersectsWith(rect2))
        {
            Rectangle overlap = Rectangle.Intersect(rect1, rect2);
            if (overlap.IsEmpty)
                return overlap.Width * overlap.Height;
        }

        return 0;
    }

Original Question:

I'd like to know a quick and dirty way to check if two rectangles overlap and if they do calculate the area of the overlap. For curiosities sake I'm interested in the case where 1) all the lines in both rectangles are either vertical or horizontal or 2) the general case for any two rectangles, but the only answer I really need is case 1.

I'm thinking along the lines of:

double areaOfOverlap( Rect A, Rect B)
{
    if ( A.Intersects(B) )
    {
        // calculate area
        // return area
    }

    return 0;
}

For A.Intersects() I was thinking of using the separating axis test, but if the rectangles have only horizontal and vertical lines is there an even simpler (faster) way to check?

And for calculating the area where they intersect is there an quick way to do it if the rectangles only horizontal and vertical lines?

Finally, this is unrelated to the question but I'd appreciate any advice someone may have on a good book / webpage where I could review the math for computer graphics. I've been out of college for a while and feel like I'm forgetting everything :)! Anyone else have that problem?

( NOTE: I found this question different than this which seems more complicated and doesn't directly answer the question. )

+4  A: 

Maybe I misinterpret your question, but doesn't the Rectangle.Intersect method do the job? It returns the intersecting area, and then you can easily calculate the area of it.

Fredrik Mörk
yes, that's prefect :). thanks!
Evan
A: 

Sounds like basic Collision Detection. Have you looked at this page on Wikipedia?

Mike

edit: Fredrik make his response at the same time I made this one, his answer got my upvote ( :

Mike B
Thanks, I'll check out the site!
Evan