The 3D formula for calculating the distance between a point and a line

Can anyone provide me with a computer program or algorithm that calculates the distance between a point and a line in a three-dimensional space? The program can be written in JavaScript or any other programming language. In this scenario, P represents the point, while A and B represent two points on the line.

P=(4,2,1);
A=(1,0,1);
B=(1,2,0);

Answer №1

When looking for the point X that is closest to the point P on the line (A, V), it is important to find the point where the line (X, P) is normal to the line (A, B).

For a line defined by two points A and B, a Unit vector D that gives the direction of the line can be calculated as follows (Note that the length of a unit vector is 1):

D = normalize(B-A);

To use the following formula, a point O on the line is required, such as O = A.

Now, the closest point X to the point P on the line (O, D) needs to be determined.

First, calculate a vector V from O to P:

V = P - O;

The distance d from O to the intersection point (closest point) X can be calculated using the Dot product.
In general, the dot product of two vectors is equal to the cosine of the angle between the two vectors multiplied by the magnitude (length) of both vectors.

dot( A, B ) == | A | * | B | * cos( angle_A_B ) 

https://i.sstatic.net/IoXGA.png

Since D is a unit vector, the dot product of V and D is equal to the cosine of the angle between the line (O, D) and the vector V, multiplied by the magnitude (length) of V:

d = dot(V, D);

The intersection point X can be calculated by moving the point O along the line (D) by the distance d:

X = O + D * d;    

Therefore, the formula for the intersection point is:

O ... any point on the line
D ... unit vector pointing in the direction of the line
P ... the "Point"

X = O + D * dot(P-O, D); 

https://i.sstatic.net/3s0V5.png

The calculation involving points on the line A, B, and the point P is as follows:

D = normalize(B-A);
X = A + D * dot(P-A, D);

The dot Product for 3-dimensional cartesian coordinates can be expressed as:

dot(A, B) = Ax*Bx + Ay*By + Az*Bz

A normalized vector (unit vector) can be calculated by:

len(A) = sqrt(Ax*Ax + Ay*Ay + Az*Az)
normalize(A) = A / len(A)

In pure Javascript, this can be calculated as follows:

var P=[4,2,1];
var A=[1,0,1];
var B=[1,2,0];

var AB    = [B[0]-A[0], B[1]-A[1], B[2]-A[2]];
var lenAB = Math.sqrt(AB[0]*AB[0] + AB[1]*AB[1] + AB[2]*AB[2]);

var D  = [AB[0]/lenAB, AB[1]/lenAB, AB[2]/lenAB];
var AP = [P[0]-A[0], P[1]-A[1], P[2]-A[2]];

var d = D[0]*AP[0] + D[1]*AP[1] + D[2]*AP[2];

var X = [A[0] + d * D[0], A[1] + d * D[1], A[2] + d * D[2]];

This can also be achieved using Three.js - Vector3, where vector arithmetic operations like add, sub, dot, and normalize are provided:

var P = new THREE.Vector3(4, 2, 1);
var A = new THREE.Vector3(1, 0, 1);
var B = new THREE.Vector3(1, 2, 0);

var D = B.clone().sub(A).normalize();
var d = P.clone().sub(A).dot(D);
var X = A.clone().add(D.clone().multiplyScalar(d)); 

Answer №2

If you need to find the distance between a point and a line in a 3D space, you can rely on the Line3 class provided by three.js to handle the calculation for you.

var line = new THREE.Line3(); // initialize the Line3 object for reuse

var P = new THREE.Vector3(); // create Vector3 objects for points
var A = new THREE.Vector3();
var B = new THREE.Vector3();
var C = new THREE.Vector3();

P.set( 4, 2, 1 );
A.set( 1, 0, 1 );
B.set( 1, 2, 0 );

// find the closest point C on the infinite line AB to point P
line.set( A, B ).closestPointToPoint( P, false, C ); 

var distance = P.distanceTo( C ); // calculate the distance between P and C

console.log( distance ); // output the calculated distance

Using version r.97 of three.js

Answer №3

Point=Pnew THREE.Vector3(4,2,1);
Start=new THREE.Vector3(1,0,1);
End=new THREE.Vector3(1,2,0);

Normal=End.clone().sub(Start).normalize()

Distance = Normal.multiplyScalar(Point.sub(Start).dot(Normal)).add(Start).sub(Point).length()

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Exploring the Power of Destructuring Results in React.js with Apollo

I have been exploring the Apollo client for my project, and I encountered an issue with two of my query functions. The first query, which retrieves a list of users, is working perfectly fine. However, I am struggling to understand why my second simple quer ...

Waiting for Capybara to wait for the AJAX to finish loading

Hello, I am experiencing an issue with my capybara testing environment. Error: jQuery is not defined (Session info: chrome=43.0.2357.125) I suspect that this problem may be related to the ajax wait function. def wait_for_ajax Timeout.timeou ...

Mastering linear regression calculations using vue.js and chart.js

Take for instance, with the current dataset, I am looking to showcase a linear regression I managed to do this in Vista and now I need guidance on how to proceed with the calculation. I am not too familiar with using the formula Here is my HTML: <canva ...

The step-by-step guide to testing an Angular promise using Jasmine

An issue arises when attempting to test the code below using Jasmine, as the console.log in `then` is never called. The question remains: is this problem related to Angular or Jasmine? describe("angular test", function() { var $q; ...

There seems to be an issue with displaying the meta information in a Nuxtjs project using this.$

I am facing an issue with meta information in a Vue page. When I try to access "this.$route.meta", it does not display any meta information. However, when I inspect the Vue page element, I can see that there is indeed meta information present. How can I ...

Updating Bootstrap 5.3 Modal to Have a Fixed Backdrop when Opened (Using JavaScript/JQuery)

Is there a way to change the backdrop of an open modal to 'static' using jQuery or JavaScript? I want to prevent the user from closing the modal by clicking outside after they have clicked the 'Submit' button on the modal. I've tri ...

What is the best way to extract the information from the checkbox in a MUI datatable?

I am struggling to transfer an array with checked values to another table in order to display only those values. How can I achieve this? I am relatively new to using react and I find it challenging to grasp how some of the functions and components work. I ...

Searching for an object in Vue 3 Composition API and displaying its contents

Experiencing a challenge with my first Vue.js project, seeking assistance in resolving the issue. Upon receiving a response from my API, I retrieve a list of projects and aim to locate the one matching the ID provided in the URL parameter. A peculiar error ...

Validating Two DateTime Pickers as a Group with Javascript in asp.net

How to Ensure Group Validation of Two DateTime Pickers Using JavaScript in ASP.NET ...

What are the applications of global variables in node.js?

global.test = "test"; console.log(global.test); //test but I want to accomplish this: console.log(test); //test without using: var test = global.test; Is there a way to achieve this? I am looking for a solution where any module in my project does not ...

Encountering the Extjs 3.4 error ERR_UNKNOWN_URL_SCHEME while trying to access a legitimate JSON

Using Extjs 3.4, I am working on a simple ajax request: Ext.Ajax.request({ url: "localhost:3000/offers.json", success: function(response, opts) { var obj = Ext.decode(response.responseText); console.dir(obj); }, failure: funct ...

Utilizing 'Ng-If' causes a glitch in the program during the execution of a $( '#x' ).change event or when adding a new item with AngularFire $add

After implementing ng-if in my code, I observed two specific instances where it caused unexpected behavior. The first instance involves using ng-if="isOwnProfile" for an image-upload toolbar. However, the use of ng-if resulted in the event listener ceasin ...

Replace the checkbox display heading with a text box in the designated area

I'm new to using kendo ui Currently, I am attempting to show a text box in the first column header. Instead of the checkboxDisplay heading, I want to replace it with a text box. Could someone please provide guidance on how to resolve this issue? Here ...

What steps can be taken to update the cart if all products have been removed?

How can I implement a refresh for my cart page every time the product length is 0 without causing unreachable code? It seems like there must be a simple solution to this problem. switch (action.type){ case "REMOVE_PRODUCT": return ...

Node.js put method fails to properly update the model in the database

Even though the code runs without any errors in the console, the field 'check' still doesn't change to true state. Why could this be happening? apiRoutes.put('/intake/:id', function(req, res) { var id = req.params.id; Intake. ...

Vue.js Contact Form Issue: Error message - 'Trying to access 'post' property of an undefined object'

Currently, I am encountering the error 'cannot read property 'post' of undefined' in my code, but pinpointing the exact mistake is proving to be a challenge. Given that I am relatively new to Vue JS, I would greatly appreciate it if som ...

Executing several API endpoint requests using an array in Node.js

Having difficulty utilizing values from an array to make API calls to endpoints. The array contains necessary data to retrieve the information needed from the endpoint. However, when attempting to parse the JSON text received from the API call and extract ...

Leveraging Leaflet or any JavaScript library alongside Typescript and webpack for enhanced functionality

Important: Despite extensive searching, I have been unable to find a resolution to my issue. My current endeavor involves developing a map library through the extension of leaflet. However, it appears that I am encountering difficulties with utilizing js ...

What is the easiest way to locate the ID of an iframe embedded within a webpage?

Currently, I am focused on developing small JavaScript/HTML5 ads for a webpage. Each advertisement comes with its own iframe that occupies a specific size and space on the page. In order to accommodate an expandable ad that needs to surpass the predetermin ...

Document ready not functioning properly for redirects

My code below seems to have an issue as it is not directing to the link specified. <html> <head> <script type="text/javascript" src="<?= baseurl(); ?>/public/js/jquery-1.9.1.min.js"></script> <script type=" ...