user2890234
user2890234

Reputation: 374

Finding closest vector to point

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

Answers (1)

Gerhard Stein
Gerhard Stein

Reputation: 1563

Okay, this is more of a math question, but let me explain it here anyways. Take a look at this picture:

Line segment definition for distances

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:

  1. With the dot product of a and AP (vector from A to P) you get the projection projA on a where the where P is closest.
  2. If you set A+ (projA)*na (na is the the normalized a vector) you get the closest Point in the vector a of P.
  3. Let's set dA = A+projA*na - P and with its length you get the closest distance to compare.

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

Related Questions