Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java collision detection between two Shape objects?

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.

like image 584
Monkeybro10 Avatar asked Mar 28 '13 19:03

Monkeybro10


1 Answers

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

like image 78
user2221343 Avatar answered Sep 28 '22 14:09

user2221343