Java collision detection between two Shape objects?

Monkeybro10 picture Monkeybro10 · Mar 28, 2013 · Viewed 32.3k times · Source

I would like to know the best way to tell if a Shape object intersects another shape. Currently I have collision detection in my game sorted out as long as it involves a Shape intersecting a Rectangle or vice versa. The problem I'm having is that the intersects() method in the Shape class can only take a Rectangle or a Point as a parameter, not another Shape. Is there an efficient way to test if two Shape objects are overlapping in any way? One way I tried was using a for loop to generate an area of points to test if they were in the shape, and then building an array of Point objects to send to the other shape to test, but this significantly dropped my framerate because of all of the unnecessary comparisons.

I looked and looked for something similar on here but didn't find anything really. Sorry in advance if this is a repeat.

Answer

user2221343 picture user2221343 · Mar 28, 2013

Not tested, but why not:

import java.awt.geom.Area;

...

public static boolean testIntersection(Shape shapeA, Shape shapeB) {
   Area areaA = new Area(shapeA);
   areaA.intersect(new Area(shapeB));
   return !areaA.isEmpty();
}

Area implements Shape, but adds some potentially useful methods