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


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
| improve this answer | |
  • \$\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 Oct 13 '16 at 10:09
  • \$\begingroup\$ @jsmars i edited it, i miss understood your question, look at the end. \$\endgroup\$ – Haruko Oct 13 '16 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 Oct 13 '16 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 Oct 13 '16 at 10:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.