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?
The cross product of A B → and A C → equal to 0 means that the vectors are colinear or that the points and or and coincide. If the cross product is not equal to zero, the point doesn't belongs on the segment.
Approach: In order for the given point to lie on the line, it must satisfy the equation of the line. Check whether y = (m * x) + c holds true. Below is the implementation of the above approach: C++
Find the distance of point P from both the line end points A, B. If AB = AP + PB, then P lies on the line segment AB.
AB = sqrt((x2-x1)*(x2-x1)+(y2-y1)*(y2-y1)+(z2-z1)*(z2-z1)); AP = sqrt((x-x1)*(x-x1)+(y-y1)*(y-y1)+(z-z1)*(z-z1)); PB = sqrt((x2-x)*(x2-x)+(y2-y)*(y2-y)+(z2-z)*(z2-z)); if(AB == AP + PB) return true;
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With