Hi I am trying to make this constructor: public Rectangle createIntersection(Rectangle r){ ....
to return a new Rectangle object representing the intersection of this Rectangle with the specified Rectangle.
So far I have done this for the constructor, but I am not sure if it is correct:
public Rectangle createIntersection(Rectangle r) {
Rectangle r1 = new Rectangle () ;
Rectangle r2 = new Rectangle ();
r2.setRect(r);
r2.createIntersection(r1);
return r2;
}
Then I am supposed to create this constructor public Boolean intersects (Rectangle r)
to return true if this intersect the specified Rectangle and return false if not. They are said to intersect if their interiors overlap. So I know for this that I need to use the four instance variables, I have been using (int x int y int height and int width). I know it has to figure out if it is intersecting by doing x + width
and if this value is less than the point across from it then the rectangles are overlapping. I'm not sure how to write this.
This method returns the overlapping area of two rectangles, or null if they do not overlap:
public static Rectangle createIntersection(Rectangle r1, Rectangle r2) {
// Left x
int leftX = Math.max(r1.x, r2.x);
// Right x
int rightX = (int) Math.min(r1.getMaxX(), r2.getMaxX());
// TopY
int topY = Math.max(r1.y,r2.y);
// Bottom y
int botY = (int) Math.min(r1.getMaxY(), r2.getMaxY());
if ((rightX > leftX) && (botY > topY)) {
return new Rectangle(leftX, topY, (rightX - leftX), (botY -topY));
}
return null;
}
Some testing :
public static void main(String [] args) {
Rectangle r1 = new Rectangle(10,10,10,10);
Rectangle r2 = new Rectangle(10,10,10,10);
System.out.println(createIntersection(r1, r2));
r1 = new Rectangle(10,10,10,10);
r2 = new Rectangle(15,15,10,10);
System.out.println(createIntersection(r1, r2));
r1 = new Rectangle(20,20,10,10);
r2 = new Rectangle(15,15,10,10);
System.out.println(createIntersection(r1, r2));
r1 = new Rectangle(15,30,10,10);
r2 = new Rectangle(15,15,10,10);
System.out.println(createIntersection(r1, r2));
r1 = new Rectangle(15,30,10,10);
r2 = new Rectangle(15,15,10,20);
System.out.println(createIntersection(r1, r2));
}
Don't hesitate to ask if the code is not clear.