Search code examples
javamathselectionshapescontain

Java check if two rectangles overlap at any point


I have multiple rectangles and one special rectangle: the selection rect. I want to check for each rectangle if the rectangle contains at least one point which is inside the selection rectangle. Here is an image for clarity:

Selection example


Solution

  • This will find if the rectangle is overlapping another rectangle:

    public boolean overlaps (Rectangle r) {
        return x < r.x + r.width && x + width > r.x && y < r.y + r.height && y + height > r.y;
    }