# Help with sorting list by distance

 0 Hi guys, before asking my question i searched for about an hour over internet and i didnt find any explanation of what is happening to my list. Here's what i want to do : I want to sort my ennemies by their distance to my tower ( tower defense ). It works pretty well, my only problem is that my tower always attack the furthest of the list. Thanks if you can help me ! Thanks anyway if you cant ! :) ``````if(targets.Count > 0) { targets.Sort(delegate(Transform t1, Transform t2) { return Vector3.Distance(t1.position, transform.position) .CompareTo(Vector3.Distance(t2.position, transform.position)); } ); closestEnemy = targets[0]; `````` more ▼ asked May 11 '12 at 05:00 PM Stonemove420 22 ● 2 ● 4 ● 8 Good questtion BUDDY May 11 '12 at 05:43 PM Toy add new comment (comments are locked) 10|3000 characters needed characters left ▼ Viewable by all users

 0 This is due to CompareTo. You can either invert the distance ( Sort( delegate(..){ -D1.CompareTo(-D2); } )) or read the list from end to start instead of start to end, depending on what you do now.By the way, you should compare the sqrMagnitude of the (t1.position - transform.position) to spare a square root, same for t2. Or even better, as I suspect the movements are 2D, compare (x1*x1 + z1*z1) to (x2*x2 + z2*z2). more ▼ answered May 11 '12 at 05:12 PM Berenger 11k ● 12 ● 19 ● 53 add new comment (comments are locked) 10|3000 characters needed characters left ▼ Viewable by all users

By Email: