Three.js - 如何判断一个点是否在一条线上?

Jar*_*gue 6 javascript 3d vector three.js

如何确定点 (x,y,z) 是否位于 A 点和 B 点之间的直线上?

我想要的是一个可以执行此操作的布尔函数:

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');
}
Run Code Online (Sandbox Code Playgroud)

这是用于可视化的图像:

在此输入图像描述

Qbi*_*bic 2

两个向量的叉积可以帮助我们解决这个问题。

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;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

一个电话:

THREE.isPointOnLineAndBetweenPoints(new THREE.Vector3(1, 0, 0), new THREE.Vector3(2, 0, 0), new THREE.Vector3(2, 0, 0));
Run Code Online (Sandbox Code Playgroud)

如果您想知道该点是否在一条线上,请使用以下函数:

isPointOnLine(new THREE.Vector3(1, 0, 0), new THREE.Vector3(2, 0, 0), new THREE.Vector3(2, 0, 0));
Run Code Online (Sandbox Code Playgroud)