Is there a circle class in Java like the Rectangle class

user1871085 picture user1871085 · Dec 2, 2012 · Viewed 24.9k times · Source

Hey I was writing a quick program and something came across where I need to use a circle for collision detection. But as far as I know, there is only the Rectangle class that has the .intersects(Point p) method. Is there anything like a circle that I could use the same way?

Answer

In silico picture In silico · Dec 2, 2012

There is a class called Ellipse2D in the java.awt.geom package that you can use, since it has some methods that appears to be what you're looking for. An ellipse with a width equal to its height is a circle.

One of the overloads for contains allows you to test for circle-point collisions:

boolean contains(double x, double y) 

Tests if the specified coordinates are inside the boundary of the Shape, as described by the definition of insideness.

Another function called intersects allows you to test for circle-rectangle collisions:

boolean intersects(double x, double y, double w, double h)

Tests if the interior of the Shape intersects the interior of a specified rectangular area.

Note that Ellipse2D is an abstract class; you would use one of its nested subclasses Ellipse2D.Double or Ellipse2D.Float, the only difference being the data type used to store the dimensions.