2014-02-07 72 views
0

林想知道你們中的任何人是否可以看看我的方法代碼,並幫助我找出是什麼原因造成的?這是一個簡單的任務,可以確定是否兩個矩形重疊/攔截/觸摸海誓山盟。我在論壇上搜索並研究了分離軸測試/定理。有用。部分地。但是,當我有兩個不具有相同尺寸的矩形時,會發生問題。 繼承人的代碼:故障排除方法

public boolean contains(MyRectangle2D x, MyRectangle2D y){ 

    if(Math.abs(xAxisDistance(x, y)) - Math.abs(centerToPerimeterXDistance(x)) - Math.abs(centerToPerimeterYDistance(y)) > 0) 
     return false; 
    if(Math.abs(yAxisDistance(x, y)) - Math.abs(centerToPerimeterXDistance(x)) - Math.abs(centerToPerimeterYDistance(y)) > 0) 
     return false; 
    else 
     return true; 
} 

public double xAxisDistance(MyRectangle2D x, MyRectangle2D y){ 
    return x.getXCenter() - y.getXCenter(); 
} 
public double yAxisDistance(MyRectangle2D x, MyRectangle2D y){ 
    return x.getYCenter() - y.getYCenter(); 
} 
public double centerToPerimeterXDistance(MyRectangle2D x){ 
    return x.getWidth()/2; 

} 

public double centerToPerimeterYDistance(MyRectangle2D x){ 
    return x.getHeight()/2; 
} 

簡而言之:我有兩個IF-句子。一個檢查x軸,另一個檢查y軸。如果圓圈之間的距離小於0,它們會重疊。當圓圈具有相同的尺寸時,它可以正常工作,但如果一個圓圈的eksample的高度較大。它在遠處時「重疊」。

任何可以促使我朝着正確的方向解決這個問題的輸入是令人滿意的!

Heres what the program looks like

+1

我無法重現您的問題。可能你的錯誤是在代碼的另一部分。 (也許在'MyRectangle2D'中有一個錯誤的getter或setter?) – Kayz

+0

是的,那很可能。生病了看着它! – Surangie

回答

0

的錯誤是在我的包含方法。

我本來應該減去兩個矩形的centerToPerimeterXDistance。 但相反,我有centerToPerimeter_Y_Distance混入。只是將其更改爲X.它像一個魅力:D

0

我不知道你是否在談論第二段「圈」。無可否認,我目前還沒有完全理解您實際在計算的內容。

然而,suggestsion:對於相交測試,一些小的輔助方法可能會有所幫助...:

private static float getMinX(MyRectangle2D r) 
{ 
    return r.getXCenter() - r.getWidth()/2; 
} 
private static float getMinY(MyRectangle2D r) 
{ 
    return r.getYCenter() - r.getHeight()/2; 
} 
private static float getMaxX(MyRectangle2D r) 
{ 
    return r.getXCenter() + r.getWidth()/2; 
} 
private static float getMaxY(MyRectangle2D r) 
{ 
    return r.getYCenter() + r.getHeight()/2; 
} 

有了這些,路口測試變得相當簡單:

private static boolean intersect(MyRectangle r0, MyRectangle r1) 
{ 
    if (getMaxX(r0) < getMinX(r1)) return false; 
    if (getMaxY(r0) < getMinY(r1)) return false; 
    if (getMinX(r0) > getMaxX(r1)) return false; 
    if (getMinX(r0) > getMaxY(r1)) return false; 
    return true; 
} 
+0

它應該是第二段中的矩形,對不起:P – Surangie