How would I find out if a point (x,y,z) is on a line between pointA and pointB?
What I would like is a boolean function that would do this:
pointA // random THREE.Vector3
pointB // random THREE.Vector3
pointToCheck // random THREE.Vector3
var isOnLine = THREE.pointOnLine(pointA, pointB, pointToCheck)
if (isOnLine) {
console.log('point is on the line');
}
Here is an image for visualization:
Cross product of two vectors can help us to solve this problem.
function isPointOnLine (pointA, pointB, pointToCheck) {
var c = new THREE.Vector3();
c.crossVectors(pointA.clone().sub(pointToCheck), pointB.clone().sub(pointToCheck));
return !c.length();
}
THREE.isPointOnLineAndBetweenPoints = function (pointA, pointB, pointToCheck) {
if (!isPointOnLine(pointA, pointB, pointToCheck)) {
return false;
}
var dx = pointB.x - pointA.x;
var dy = pointB.y - pointA.y;
// if a line is a more horizontal than vertical:
if (Math.abs(dx) >= Math.abs(dy)) {
if (dx > 0) {
return pointA.x <= pointToCheck.x && pointToCheck.x <= pointB.x;
} else {
return pointB.x <= pointToCheck.x && pointToCheck.x <= pointA.x;
}
} else {
if (dy > 0 ) {
return pointA.y <= pointToCheck.y && pointToCheck.y <= pointB.y;
} else {
return pointB.y <= pointToCheck.y && pointToCheck.y <= pointA.y;
}
}
}
a call:
THREE.isPointOnLineAndBetweenPoints(new THREE.Vector3(1, 0, 0), new THREE.Vector3(2, 0, 0), new THREE.Vector3(2, 0, 0));
Use the following function if you wanna to know just whether this point is on a line or not:
isPointOnLine(new THREE.Vector3(1, 0, 0), new THREE.Vector3(2, 0, 0), new THREE.Vector3(2, 0, 0));
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