这个简单的圆/矩形碰撞检测有什么问题?

时间:2014-10-07 22:25:07

标签: java collision geometry rectangles

我有一个简单的2d碰撞检测问题,有圆形和矩形。所有检查器都会看到圆圈的中心是否与矩形上的任何点重叠。

看见检查员:

boolean overlaps(Circle circle) {   
    for (double i = topLeft.x; i < (topLeft.x + width); i++)
    {
        for (double j = topLeft.y; j < (topLeft.y + height); j++)
        {
            if (circle.center.x == i && circle.center.y == j)
            {

                return true;
            }

        }
    }
return false;
}`

非常简单,而且非常重要。该错误在我的circle.center.x和/或circle.center.y的if语句中发挥作用。

以下是我的Circle类的代码:

public class Circle {
Point center;
double radius;
/**
 * Constructor.
 * 
 * @param center  the center Point of the circle
 * @param radius  the radius of the circle
 */
public Circle(Point center, double radius) {
center = this.center;
radius = this.radius;
}

/**
 * Get the current center point of the circle.
 * 
 * @return the center point of the circle
 */
public Point getCenter() {
    return center;
}

/**
 * Set the center point of the circle.
 * 
 * @param center the (new) center point of the circle
 */
public void setCenter(Point center) {
    this.center = center;
}

/**
 * Get the current radius.
 * 
 * @return the current radius
 */
public double getRadius() {
    return radius;
}

/**
 * Set the radius.
 * 
 * @param radius the (new) radius of the circle
 */
public void setRadius(double radius) {
    this.radius = radius;
}

}`

我哪里错了?它肯定不是我的Point类的一个问题,因为这意味着现在还有很多其他的东西会出错。提前谢谢。

1 个答案:

答案 0 :(得分:0)

你的方法应该是:

boolean overlaps( Circle circle )
{
    return topLeft.x <= circle.center.x && circle.center.x <= topLeft.x + width &&
           topLeft.y <= circle.center.y && circle.center.y <= topLeft.y + height;
}