# Sorting transforms by distance to cross hair

So I’m trying to put together a targeting system for my game, I want to select the transform closest to the cross hair.

But I’m really struggling to get it working, below is my sorting code for a list of transforms in range, I want the closest to the cross hair (or centre of the screen) to be the first in the list.

Unfortunately I just don’t know enough to make it work the way I want it to. I’ve tried searching but cant find anyone really trying to do this.

If anyone can shed any light on this I would be really grateful.

``````    int SortByDistanceToMid(Transform a, Transform b)
{
Vector2 AScreenPOS = new Vector2(Mathf.Clamp(cam.WorldToViewportPoint(a.position).x - 0.5f, -0.5f, 0.5f), Mathf.Clamp(cam.WorldToViewportPoint(a.position).y - 0.5f, -0.5f, 0.5f));
Vector2 BScreenPOS = new Vector2(Mathf.Clamp(cam.WorldToViewportPoint(b.position).x - 0.5f, -0.5f, 0.5f), Mathf.Clamp(cam.WorldToViewportPoint(b.position).y - 0.5f, -0.5f, 0.5f));

float squaredRangeA = Vector2.Distance(AScreenPOS, ScreenCentre);
float squaredRangeB = Vector2.Distance(BScreenPOS, ScreenCentre);
Debug.Log(squaredRangeA + " and " + squaredRangeB);
return squaredRangeA.CompareTo(squaredRangeB);
}
``````

I don’t see why that general approach wouldn’t work. What exactly is going wrong with it?

(I notice that your function has “Sort” in the name but is actually just performing a comparison, not a sort, but I assume you already know that part. And I bet you don’t actually need the Clamp step, in which case you could simplify AScreenPOS to just `Vector2 AScreenPOS = cam.WorldToViewportPoint(a.position) - .5f * Vector2.one;`, and then do similar to B, but I doubt that difference is preventing your current code from working.)

1 Like

Okay so some brief testing later, removing the clamps seems to solve the problem! Thanks for sanity check!