x


Help with sorting list by distance

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 gravatar image

Stonemove420
22 2 4 8

Good questtion BUDDY

May 11 '12 at 05:43 PM Toy
(comments are locked)
10|3000 characters needed characters left

1 answer: sort voted first

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 gravatar image

Berenger
11k 12 19 53

(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x1949
x40

asked: May 11 '12 at 05:00 PM

Seen: 729 times

Last Updated: May 11 '12 at 05:43 PM