Search code examples
javageometrycollisionoval

Is there a way to use an Oval object with the intersects() function?


First of all, I know that there are very similar questions answered already, but I haven't seen this question in particular asked yet.

I have an oval and a rectangle and I want to detect if they are intersecting. I know you can do this with two rectangles like so:

if (new Rectangle(x1, y1, w1, h1).intersects(new Rectangle(x2, y2, w2, h2))) {

    //code here for when collision occurs.

}

Is it possible to do this with an oval like so?

if (new Oval(x1, y1, w1, h1).intersects(new Rectangle(x2, y2, w2, h2))) {

    //code here for when collision occurs.

}

Thanks in advance!


Solution

  • I do not see an Oval class when I search for one, so I will use Ellipse as an example. If you look at the docs here you will see the docs for the Shape class.

    This class is extended by both Rectangle and Ellipse and also contains an intersect(Shape, Shape) method, so therefore you will be able to use intersect on both of these objects.

    If your Oval class and Rectangle class both extend the same Shape Class in your scenario from where the intersect(Shape, Shape) is inherited from, it will work in your scenario as well.