0

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
    }
  • Is this a java.awt.geom.Rectangle? – Sinkingpoint Dec 03 '13 at 22:25
  • Read this: http://stackoverflow.com/questions/9749851/faster-way-to-check-intersected-rectangles?rq=1 – Melquiades Dec 03 '13 at 22:25
  • 1
    Could you provide some inputs on which this produces the correct outcome, and some inputs on which this produces a faulty outcome? – kviiri Dec 03 '13 at 22:25
  • Basically, a rectangle is just 4 lines. The generally approach is try and calculate the intersection points of each line individually, for [example](http://stackoverflow.com/questions/15594424/line-crosses-rectangle-how-to-find-the-cross-points/15594751#15594751) – MadProgrammer Dec 03 '13 at 22:29

1 Answers1

1

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

if ( ymax <= ymax2 )

... should be like the other if:

if ( ymax >= ymin )
Russell Zahniser
  • 16,188
  • 39
  • 30