Browse - Programming Tips - How can I test if 2 rectangles intersect?

Date: 2015nov17
Language: Java
Keywords: overlap, collision, union, ontop, inside

Q.  How can I test if 2 rectangles intersect?

A.  The Java class java.awt.Rectangle has a method for this.
So if are using it you can just call intersects()
but not you can adapt the code:

public boolean intersects(Rectangle r) { int neww = (x + width < r.x + r.width ? x + width : r.x + r.width) - (x < r.x ? r.x : x); int newh = (y + height < r.y + r.height ? y + height : r.y + r.height) - (y < r.y ? r.y : y); return (neww > 0 && newh > 0); }