2013-02-18 80 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