I've got a ray defined by P1 and P2, and then a target P3, and I want to find P4. How do I go about this? I've come to understand that I should use vector projection, but I can't get it to work. Any help? I'm using C# and XNA.

enter image description here


1 Answer 1


Closest distance point segment:

float SqDistPointSegment(Point a, Point b, Point c)
    Vector ab = b – a, ac = c – a, bc = c – b;
    float e = Dot(ac, ab);
    // Handle cases where c projects outside ab
    if (e <= 0.0f) return Dot(ac, ac);
    float f = Dot(ab, ab);
    if (e >= f) return Dot(bc, bc);
    // Handle cases where c projects onto ab
    return Dot(ac, ac) – e * e / f;

Source: Christer Ericson Real Time Collision Detection. You can find all kind of algorithms for this things in that book, take it, it is a must.

Anyways to see the distance of a point to vector is easy just do:


It gives you the distance. The vector must be normalized.

With this distance you can multiply it for the normalized vector and added to the P1 to get P4. Then:

Vector rayDir = (P2 - P1).normalize();
P4 = P1 + rayDir.Dot(P3)*rayDir
  • \$\begingroup\$ How do I use this method to get P4 from P1, P2 & P3? What are a, b, c from my example? I tried this method but it just gives me a large number which does not translate over to the length along the ray to the closest point. \$\endgroup\$
    – jsmars
    Commented Oct 13, 2016 at 10:09
  • \$\begingroup\$ @jsmars i edited it, i miss understood your question, look at the end. \$\endgroup\$
    – Haruko
    Commented Oct 13, 2016 at 10:11
  • \$\begingroup\$ Ah yes, now it works! Thanks so much! Does seem like a lot of mathematical steps to reach the target tho, I would think there should be a more efficient way to get the same result. \$\endgroup\$
    – jsmars
    Commented Oct 13, 2016 at 10:20
  • \$\begingroup\$ Actually nevermind that last comment, I just noticed that the final line doesn't use the method you posted. Looks efficient enough! :) \$\endgroup\$
    – jsmars
    Commented Oct 13, 2016 at 10:25

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .