Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Three.js - How to determine if a point is on a line?

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:

enter image description here

like image 453
Jared Sprague Avatar asked Nov 08 '22 20:11

Jared Sprague


1 Answers

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));
like image 182
Qbic Avatar answered Nov 14 '22 22:11

Qbic