首页 > 解决方案 > 有没有办法将 Oval 对象与 intersects() 函数一起使用?

问题描述

首先,我知道已经回答了非常相似的问题,但我还没有看到这个问题特别被问到。

我有一个椭圆和一个矩形,我想检测它们是否相交。我知道你可以用两个矩形来做到这一点:

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

    //code here for when collision occurs.

}

像这样的椭圆形可以做到这一点吗?

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

    //code here for when collision occurs.

}

提前致谢!

标签: javageometrycollisionoval

解决方案


我在搜索时没有看到 Oval 类,因此我将使用 Ellipse 作为示例。如果您查看此处的文档,您将看到该Shape课程的文档。

此类由两者扩展Rectangle并且Ellipse还包含一个intersect(Shape, Shape)方法,因此您将能够在这两个对象上使用相交。

如果您的Oval类和类都从继承的场景中Rectangle扩展同一个Shape类,它也将在您的场景中工作。intersect(Shape, Shape)


推荐阅读