0
votes

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 );  
2
Line3 has .closestPointToPoint() method.prisoner849
Thank you, I see this has the option to specify a line segment as well.Chewie The Chorkie

2 Answers

1
votes

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


1
votes

I'm not so proficient to write the code, but I think I can provide you at least the algorithm.

A segment can be extended to an infinite line, now you can calculate the distance from the camera point to the line; the problem is you don't know if the perpendicular to the line passing from the camera is inside or outside the segment. So you can calculate three distances: the distances between the camera point and the two points of the segment and the distance between the camera and the line, the lower of the three should be the distance you are looking for.

Hope this helps.