检查对象坐标是否符合要求

Mat*_*wek 0 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;

boolean xCorrect = false;
boolean yCorrect = false;
Run Code Online (Sandbox Code Playgroud)

我正在尝试创建算法,检查

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

 if (y == destinationY + permittedDifference || y == destinationY - permittedDifference)
 {
     yCorrect = true;
 }
Run Code Online (Sandbox Code Playgroud)

听起来最简单的方式,但也许有更好的方式?将不胜感激一些提示.

Roh*_*ain 5

你可以Math.abs()在这里使用方法.获得x和之间的绝对差异destinationX,并检查它是否小于或等于permittedDifference:

xCorrect = Math.abs(x - destinationX) <= permittedDifference;
yCorrect = Math.abs(y - destinationY) <= permittedDifference;
Run Code Online (Sandbox Code Playgroud)