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?

  • \$\begingroup\$ Take this as a tip, and not as a bash: Try thinking deeply when trying to accomplish something in programming. You have just tried to search for an algorithm and a specialised function of the engine just for a simple search in an simple array. However, you may find it hard at the start of your programming quest to get all that, but that's fine. But I'm pretty sure next time you see "I have an array" "I want to select one of the items of that array" "Based on <?> condition", you'll know what to do. \$\endgroup\$ Jun 3, 2015 at 11:49
  • \$\begingroup\$ I told you, don't take it as a bash. Its not your fault, and I've been there and I've done that. It's not a math problem anyway, shortest distance is still a predicate and selecting is still a search on an array, so it's a basic CS problem. If you choose to hear me or not, that's another matter. \$\endgroup\$ Jun 3, 2015 at 21:10
  • \$\begingroup\$ ??? Are you sure it was me? \$\endgroup\$ Jun 4, 2015 at 23:31

1 Answer 1


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.

  • \$\begingroup\$ oops! glad u figured it out! \$\endgroup\$ Jun 2, 2015 at 23:20

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .