2013-02-18 45 views
0

我正在製作遊戲,我需要檢查對象的座標是否符合要求(目的地座標)與允許的差值。檢查對象座標是否符合要求

例子:

int x; //current object X coordinate 
int y; //current object Y coordinate 

int destinationX = 50; //example X destination value 
int destinationY = 0; //example Y destination value 
int permittedDiference = 5; 

boolean xCorrect = false; 
boolean yCorrect = false; 

我想創建算法,檢查

if (x == destinationX + permittedDifference || x == destinationX - permittedDifference) 
{ 
    xCorrect = true; 
} 

if (y == destinationY + permittedDifference || y == destinationY - permittedDifference) 
{ 
    yCorrect = true; 
} 

這聽起來像最簡單的方式,但也許有更好的?將不勝感激的一些提示。

+0

其他,還有什麼可以做什麼? – 2013-02-18 21:00:20

回答

5

您可以在這裏使用Math.abs()方法。獲取xdestinationX之差的絕對值,並檢查它是否是小於或等於permittedDifference

或許比重構到`xAllowed`或`xBetween`等方法
xCorrect = Math.abs(x - destinationX) <= permittedDifference; 
yCorrect = Math.abs(y - destinationY) <= permittedDifference; 
+0

它運作良好,我只是想知道,你認爲,哪一種方法會更好地使用,更快的我的意思是,這個使用abs方法,或者你在開始時發佈的第一個方法?我會一直檢查這些「要求」,在每次更新時,針對少數對象,當然這並不需要很多計算,但我仍想知道您的意見,謝謝。 – Matim 2013-02-18 21:10:58

+0

@Matim。好吧,我沒有發佈任何其他解決方案。就速度而言,你應該不會爲此感到困擾。可讀性是這裏主要關心的問題。當使用這種方法時,它變得非常清楚,即你正在嘗試做的事情,而不是普通的「if-else」塊。另外,如果您經常進行這些測試,那麼最好在某些方法中移動這些邏輯,並給出一個有意義的名稱並調用它。這將更清晰。 – 2013-02-18 21:13:26