Posted By

jatkins on 07/07/17


Tagged

line point Geometry Vector


Versions (?)

Find shortest distance from point to line, based on two points or vector equation of a line


 / Published in: JavaScript
 

Released into the public domain by Josh Atkins, 2017.

  1. function VectorLine() {
  2. // r = c + t(d-c)
  3. if ('point1' in arguments[0] && 'point2' in arguments[0]) {
  4. this.positionVector = point1;
  5. this.directionVector = {x: point2.x - point1.x, y: point2.y - point1.y, z: point2.z - point1.z};
  6. } else if ('positionVector' in arguments[0] && 'directionVector' in arguments[0]) {
  7. this.positionVector = arguments[0].positionVector;
  8. this.directionVector = arguments[0].directionVector;
  9. }
  10. }
  11. VectorLine.prototype.shortestDistanceToPoint = function (point) {
  12. var pV1 = this.positionVector, dV = this.directionVector,
  13. pV2 = {x: pV1.x - point.x, y: pV1.y - point.y, z: pV1.z - point.z},
  14. mu = -(pV2.x * dV.x + pV2.y * dV.y + pV2.z * dV.z) / (dV.x * dV.x + dV.y * dV.y + dV.z * dV.z),
  15. xSq = Math.pow(pV2.x + dV.x * mu, 2) + Math.pow(pV2.y + dV.y * mu, 2) + Math.pow(pV2.z + dV.z * mu, 2),
  16. x = Math.sqrt(xSq);
  17.  
  18. return x;
  19. }
  20. var v1 = new VectorLine({positionVector: {x: 1, y: 1, z: -3}, directionVector: {x: 2, y: -2, z: -1}});
  21. console.log(v1.shortestDistanceToPoint({x: 1, y: 2, z: -1}));

Report this snippet  

You need to login to post a comment.