2014-10-07 21 views
-1

我用一個圓形和一個矩形進行簡單的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; 
}` 

很簡單,給點意見。 if語句出現錯誤,我的circle.center.x和/或circle.center.y

這裏是我的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

爲什麼二維循環?爲什麼不簡單不平等(即'<' or '>')檢查? – 2014-10-07 22:30:58

+0

我確實改變了它的建議,但問題仍然存在於圈子類中。 – GravityCheck 2014-10-07 22:39:23

回答

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; 
} 
+0

也許這將是更合適的,但問題存在於我的圈子類中,因爲'circle.center.x'返回null,而不是重疊方法本身。 – GravityCheck 2014-10-07 22:34:35

+0

'circle.center.x'不能返回'null',因爲它只是一個變量。它可以是'null',但只有它是引用類型而不是基元類型。 – clcto 2014-10-07 22:41:10

+0

我的意思是它給了我一個空指針異常。 – GravityCheck 2014-10-07 22:43:12