javascriptthree.js3ddistanceline-segment

Three.js distance between point and line segment


In Three.js, I have an easy method for finding the distance between a point (being the location of my camera) and a line that extends infinitely. However, what I really need is to find the distance between a point and a single line segment made from two points. Note: I'm using Three.js which has 3 spacial dimensions: x, y and z.

Here's the point to line segment formula I'm using with 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 );  

Solution

  • Method 1 With TRHEE js

    To find the distance between a point (A) and a single line segment made from two points (B and C) we can use the THREE.Vector3, which is not a mesh, it a only a geometric line.

    Vector3 has a method called closestPointToPoint(). Taking the distance provided by closestPointToPoint() method we will find the distance between the point A and the segment or line 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 ! 
    

    Method 2 With Algebra


    Having the coordinates of the points A, B and C, we can write the distance between A and the line BC with the formula given here: Math StackExchange