Home > Back-end >  Java: rectangle Overlap
Java: rectangle Overlap

Time:02-03

I need some help regarding an assignment that I've received through school. I've been stuck on a specific part of the assignment, detecting whether a rectangle is overlapping another. I tried to create an If-statement for the cases when the two rectangles aren't overlapping, but the teacher said that it would be easier doing the opposite and gave me a picture of seven scenarios that I should create If-statements for. I'm not looking for an complete answer, just maybe a solution to one of the cases so I get an idea of how I should think, or maybe just a tip. Thanks!

here is the picture,

enter image description here

The program language is Java. The rectangles have the dimensions: dx(width), dy(height). They each have coordinates: x, y. Which are located on the top left of each rectangle.

CodePudding user response:

Try to solve it for one dimension first, then the other and combine the results.

Line A would overlap line B if start of A is before end of B while at the same time end of A is after start of B.

So if these two criterions match for the horizontal coordinates, perform the same check for the vertical coordinates. Only when you have overlap both horizontally and vertically the rectangles have a common area.

In code:

boolean isOverlap(java.awt.Rectangle A, java.awt.Rectangle B) {
    if ((A.x <= B.x B.width) && (A.x A.width >= B.x)) {
        // overlap horizontally, now check vertical
        if ((A.y <= B.y B.height) && (A.y A.height >= B.y)) {
            // overlap also vertically
            return true;
        }
    }
    return false;
}
  •  Tags:  
  • Related