Except from my Rect-class:
public class Rect {
public int x;
public int y;
public int w;
public int h;
public Rect(int x, int y, int w, int h) {
this.x = x;
this.y = y;
this.w = w;
this.h = h;
}
...
}
I have a method to check if two Rects intersects (no pun intended):
public boolean intersect(Rect r) {
return (((r.x >= this.x) && (r.x < (this.x + this.w))) || ((this.x >= r.x) && (this.x < (r.x + r.w)))) &&
(((r.y >= this.y) && (r.y < (this.y + this.h))) || ((this.y >= r.y) && (this.y < (r.y + r.h))));
}
Test case:
r1 = (x, y, w, h) = (0, 0, 15, 20) center: (x, y) = (7, 10)
r2 = (x, y, w, h) = (10, 11, 42, 15) center: (x, y) = (31, 18)
r1 Intersect r2: true
The class works fine.
What I’m wondering is if there is another – perhaps faster – way to check if the rectangles are intersecting. Can I optimize it in some way?
I tend to store rectangles as min x, min y, max x and max y. Then overlap occurs when
And if they overlap, the intersection is defined by
Some care should be taken depending on whether or not you consider them to be overlapping if they have the same boundary. I’ve used strict inequalities meaning that overlapping boundaries do not count as an overlap. Given that you are using integers (and thus the boundaries have a width of 1) I will assume that you do want to consider overlapping boundaries as an overlap. I would do something like: