Reputation: 374
How can i sort vectors by distance from point? For example i have three vectors: A, B, C and the point
Example image with point and vectors
And the sorted result must be something like this: (A, C, B)
Upvotes: 1
Views: 2769
Reputation: 1563
Okay, this is more of a math question, but let me explain it here anyways. Take a look at this picture:
Let's define a line segment by vector A for the start point and a for the vector running through that line segment which end at the arrows end. Same is valid for the other segments B and C respectively. The point P as coordinates as also a vector.
Now let's make linear algebra our friend, yet be programatically efficient. :-)
At the example of segment a you can do this and with the other respectively:
Instead of saving the distances, try to store and compare squared distance of dA, dB and dC and compare those instead. It will save you to compute the square root which might become very expensive.
Here is some pseudocode:
vector3 AP = P-A;
vector3 projA = a.dot(AP);
vector3 nA = a.normalized();
dA = A + projA*na - P;
dA2 = dA.x*dA.x + dA.y*dA.y + dA.z*dA.z;
-> Compare and sort them by that value
Hope it helps a bit...
Upvotes: 2