Reputation: 1559
I am making game, where I need to check if object`s coordinates meets requirements (Destination coordinates) with permitted +- difference.
Example:
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;
I am trying to create algorithm, checking
if (x == destinationX + permittedDifference || x == destinationX - permittedDifference)
{
xCorrect = true;
}
if (y == destinationY + permittedDifference || y == destinationY - permittedDifference)
{
yCorrect = true;
}
It sounds like most simply way, but maybe there is better one? Will be grateful for some tips.
Upvotes: 0
Views: 86
Reputation: 213361
You can make use of Math.abs()
method here. Get the absolute difference between x
and destinationX
, and check whether it's less than or equal to permittedDifference
:
xCorrect = Math.abs(x - destinationX) <= permittedDifference;
yCorrect = Math.abs(y - destinationY) <= permittedDifference;
Upvotes: 5