I have an array of objects. Their position is a Vector2
. I want to select the closest object, given an X and Y coordinate that represents an user touch on screen.
How can I do this?
Game Development Stack Exchange is a question and answer site for professional and independent game developers. It only takes a minute to sign up.
Sign up to join this communityI have an array of objects. Their position is a Vector2
. I want to select the closest object, given an X and Y coordinate that represents an user touch on screen.
How can I do this?
There isn't any libGDX function for this particular problem, but it should be something like:
Vector2 closestToFinger(Vector2[] vectorsArray, Vector2 touchPosition)
{
float shortestDist = 0;
Vector2 closestVector = null;
for(point in vectorsArray){
float dst2 = touchPosition.dst2(point);
if(closesVector == null || dst2 < shortestDist){
shortestDist = dst2;
closestVector = point;
}
}
return closestVector;
}
Also, when iterating through your array, using the dst2()
function rather than dst()
will improve performance because it doesn't need to calculate a square root.