Dave's Brain

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); }

Add a comment

Sign in to add a comment
Copyright © 2008-2017, dave - Code samples on Dave's Brain is licensed under the Creative Commons Attribution 2.5 License. However other material, including English text has all rights reserved.