Java 检查对象坐标是否符合要求
我在做游戏,我需要检查物体的坐标是否符合要求(目的地坐标),允许+-差 例如:Java 检查对象坐标是否符合要求,java,Java,我在做游戏,我需要检查物体的坐标是否符合要求(目的地坐标),允许+-差 例如: 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;
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;
}
这听起来是最简单的方法,但也许有更好的方法?我们将非常感谢您提供一些提示。您可以在此处使用此方法。获取x
和destinationX
之间的绝对差异,并检查其是否小于或等于许可差异
:
xCorrect = Math.abs(x - destinationX) <= permittedDifference;
yCorrect = Math.abs(y - destinationY) <= permittedDifference;
xCorrect=Math.abs(x-destinationX)您可以使用这里的方法。获取x
和destinationX
之间的绝对差异,并检查其是否小于或等于许可差异
:
xCorrect = Math.abs(x - destinationX) <= permittedDifference;
yCorrect = Math.abs(y - destinationY) <= permittedDifference;
xCorrect=Math.abs(x-destinationX)除了可能重构为xAllowed
或xBetween
等方法之外,你还能做什么?除了可能重构为xAllowed
或xBetween
等方法之外,你还能做什么?它工作得很好,我只是想知道,你认为呢,使用哪种方法更好,更快,我的意思是,这一种使用abs方法,还是您在开始时发布的第一种方法?每次更新时,我都会检查这些“要求”,对于一些对象,当然这不需要很多计算,但我还是想知道你的意见,谢谢。@Matim。嗯,我没有发布任何其他解决方案。就速度而言,你真的不应该为此烦恼。可读性是这里主要关注的问题。使用这种方法时,很明显,您要做的是,而不是正常的if-else
block。另外,如果您经常做这些测试,那么最好在某些方法中移动这些逻辑,并给它一个有意义的名称,然后调用它。这会更清楚。它工作得很好,我只是想知道,你认为哪种方法更好,更快,我的意思是,这一种使用abs方法,还是你在开始时发布的第一种方法?每次更新时,我都会检查这些“要求”,对于一些对象,当然这不需要很多计算,但我还是想知道你的意见,谢谢。@Matim。嗯,我没有发布任何其他解决方案。就速度而言,你真的不应该为此烦恼。可读性是这里主要关注的问题。使用这种方法时,很明显,您要做的是,而不是正常的if-else
block。另外,如果您经常做这些测试,那么最好在某些方法中移动这些逻辑,并给它一个有意义的名称,然后调用它。这将更加清楚。