Question
How can I verify if a projected point on a line segment is contained within the segment's endpoints?
// Function to check if point P lies on line segment AB
function isPointOnSegment(A, B, P) {
// Check if the point P is within the bounding box of A and B
let crossProduct = (P.y - A.y) * (B.x - A.x) - (P.x - A.x) * (B.y - A.y);
if (Math.abs(crossProduct) > Number.EPSILON) return false; // Not collinear
let dotProduct = (P.x - A.x) * (B.x - A.x) + (P.y - A.y) * (B.y - A.y);
if (dotProduct < 0) return false; // Not between A
let squaredLengthAB = (B.x - A.x) * (B.x - A.x) + (B.y - A.y) * (B.y - A.y);
return dotProduct <= squaredLengthAB; // Check if within AB
}
Answer
To check whether a point lies on a line segment defined by two endpoints, we can use vector mathematics to confirm if the point is both collinear and bounded by the two endpoints.
// Example usage
let A = {x: 1, y: 1};
let B = {x: 4, y: 4};
let P = {x: 2, y: 2}; // Point to check
console.log(isPointOnSegment(A, B, P)); // Returns true if P is on segment AB
Causes
- The point is outside the bounds of the segment.
- The point is not collinear with the segment.
Solutions
- Utilize vector cross products to verify collinearity.
- Compare the components of the point's coordinates against the segment's endpoints to confirm containment.
Common Mistakes
Mistake: Assuming a point can be checked without vector calculations.
Solution: Remember to use cross products to check for collinearity.
Mistake: Not accounting for exact boundaries.
Solution: Always compare dot products with the lengths to ensure the point is within both endpoints.
Helpers
- line segment
- check point inside segment
- point projection
- geometry point check
- JavaScript line segment check