Search code examples
c#algorithm3dpoint

Find if point lies on line segment


I have line segment defined by these two points: A(x1,y1,z1) and B(x2,y2,z2). I have point p(x,y,z). How can I check if the point lies on the line segment?


Solution

  • If the point is on the line then:

    (x - x1) / (x2 - x1) = (y - y1) / (y2 - y1) = (z - z1) / (z2 - z1)
    

    Calculate all three values, and if they are the same (to some degree of tolerance), your point is on the line.

    To test if the point is in the segment, not just on the line, you can check that

    x1 < x < x2, assuming x1 < x2, or
    y1 < y < y2, assuming y1 < y2, or
    z1 < z < z2, assuming z1 < z2