Game Development Stack Exchange is a question and answer site for professional and independent game developers. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Let's say I have a line defined by two points, A and B, both in the form (x, y, z). These points represent a line in 3D space.

I also have a point P, defined in the same format, that isn't on the line.

How would I calculate the projection of that point on to the line? I'm aware of how to do this in 2D but 3D seems to have bugger all resources on it.

share|improve this question

You simply need to project vector AP onto vector AB, then add the resulting vector to point A.

Here is one way to compute it:

A + dot(AP,AB) / dot(AB,AB) * AB

This formula will work in 2D and in 3D. In fact it works in all dimensions.

share|improve this answer

Here's a fast and easy way to do it in python:

from numpy import *
def ClosestPointOnLine(a, b, p):
    ap = p-a
    ab = b-a
    result = a + dot(ap,ab)/dot(ab,ab) * ab
    return result
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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