-2

Hello :) I'm currently working on something that hinges on checking the overlap of two rectangles in Java on BlueJ, and I've been checking the internet stuck for hours for anything to help but I've not managed to find anything which helps which is specific enough to what I'm dealing with.

Currently, I'm writing a method called "checkOverLap" and it looks a little like this:

private Boolean checkOverlap() {
    if (word2.getXPosition() >= word1.getXPosition() && word2.getXPosition() <= word1.getXPosition() + word1.getTextWidth() && (word2.getYPosition() >= word1.getYPosition() && word2.getYPosition() <= word1.getYPosition() + word1.getTextHeight())){
        return true;
    }

    else{
        return false;
    }

}

Erm, I'm relatively new to Java, so please forgive how horrendously this is formatted >.>

The general gist of what it needs to do, is to return true when the rectangles overlap :) Else, it will return false. The reason this is required, is because I want the rectangles to randomize their position on the screen until they overlap.

I have already included accessor methods which return the X and Y coordinates and the Width and Height of the rectangles, and these are what I am using in the if statement to compare and see if they over lap.

As to whats wrong with it, I'm currently unsure but I'm thinking it's to do with the logic of the statement, like I haven't compared the right variables etc or I've added the wrong operators :/

Any advice or such would be appreciated :)

1 Answers1

0

You don't have to do it yourself. Use the intersects method of java.awt.Rectangle instead:

final Rectangle r1 = new Rectangle(50, 50, 10, 10);
final Rectangle r2 = new Rectangle(40, 40, 10, 10);
final Rectangle r3 = new Rectangle(40, 40, 15, 15);

System.out.println(r2.intersects(r1)); // false
System.out.println(r3.intersects(r1)); // true
Quagaar
  • 1,257
  • 12
  • 21