user3063453
user3063453

Reputation: 1

Finding the intersection of 2D rectangle in JAVA

Help! Been looking for hours now, each rectangle object consists of x co-ordinate, y co-rdinate, height and width of a rectangle

any help to where im going wrong would be a relief please! thank you in advance.

public static boolean intersection(Rectangle r1, Rectangle r2) {
        int xmin = Math.max(r1.x, r2.x);    //find the maximum minimum x co-ordinate value between rectangle 1 and 2 entered
        int xmax1 = r1.x + r1.width;    //finds max co-ordinate for rectangle 1
        int xmax2 = r2.x + r2.width;    //finds max co-ordinate for rectangle 2
        int xmax = Math.min(xmax1, xmax2);  //out of both max rect 1 and 2, take minimum as this is where would intersect
        if (xmax >= xmin) { //if true then its in the same x co-ordinates
            int ymin = Math.max(r1.y, r2.y);    //do same for y co-ordinate
            int ymax1 = r1.y + r1.height;
            int ymax2 = r2.y + r2.height;
            int ymax = Math.min(ymax1, ymax2);
            if ( ymax <= ymax2 )    //if in-between this, then two rectangles intersects
                return true;    
        }
        return false;   //else doesn't intersect
    }

Upvotes: 0

Views: 352

Answers (1)

Russell Zahniser
Russell Zahniser

Reputation: 16354

It looks like the only problem in your code is that this:

if ( ymax <= ymax2 )

... should be like the other if:

if ( ymax >= ymin )

Upvotes: 1

Related Questions