在Three.js中,我有一个简单的方法来找到一个点(是我的相机的位置(和无限延伸的线之间的距离。但是,我真正需要的是找到一个点和由两个点组成的单个线段之间的距离。注意:我使用的是 Three.js它有 3 个空间维度:x、y 和 z。
这是我与 Three.js 一起使用的点到线段公式:
var A = lineVertex1.clone()
var B = lineVertex2.clone()
var D = B.clone().sub( A ).normalize();
var d = camera.position.clone().sub( A ).dot( D );
var X = A.clone().add( D.clone().multiplyScalar( d ) );
var distance = camera.position.distanceTo( X );
方法 1 使用 TRHEE js
要找到点 (A( 和由两个点(B 和 C(组成的单个线段之间的距离,我们可以使用 THREE。Vector3,它不是一个网格,它只是一条几何线。
Vector3 有一个名为 closestPointToPoint(( 的方法。取 closestPointToPoint(( 方法提供的距离,我们将找到点 A 与段或线 BC 之间的距离。
const A=new Vector3(0,0,0);
const B=new Vector3(5,2,5); // line base point 1
const C=new Vector3(5,-2,5); // line base point 2
const line=new Line3(B,C);
const d=line.closestPointToPoint(A).distanceTo(A);
console.log(d.toFixed(3));// 7.071 this is 5 × √2 !
方法2 代数
有了点 A、B 和 C 的坐标,我们可以使用这里给出的公式写出 A 和线 BC 之间的距离: 数学堆栈交换
我不太精通编写代码,但我认为我至少可以为您提供算法。
一段可以延伸到无限条线,现在你可以计算从相机点到线的距离;问题是你不知道垂直于从相机通过的线是在线段内还是线外。所以你可以计算三个距离:相机点和线段的两个点之间的距离以及相机和线之间的距离,三者中较小的应该是您要查找的距离。
希望这有帮助。
上面答案中的line.closestPointToPoint已被弃用。请参阅Line3.closestPointToPoint。正确的代码:
const A=new Vector3(0,0,0);
const B=new Vector3(5,2,5); // line base point 1
const C=new Vector3(5,-2,5); // line base point 2const target = new
const line=new Line3(B,C);
const target = Vector3();
line.closestPointToPoint( A, false, target );
const d = target.distanceTo( A );
console.log(d.toFixed(3));// 7.071 this is 5 × √2 !