## Posted By

jatkins on 07/07/17

# 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.

`function VectorLine() {	// r = c + t(d-c)	if ('point1' in arguments[0] && 'point2' in arguments[0]) {		this.positionVector = point1;		this.directionVector = {x: point2.x - point1.x, y: point2.y - point1.y, z: point2.z - point1.z};	} else if ('positionVector' in arguments[0] && 'directionVector' in arguments[0]) {		this.positionVector = arguments[0].positionVector;		this.directionVector = arguments[0].directionVector;	}}VectorLine.prototype.shortestDistanceToPoint = function (point) {	var pV1 = this.positionVector, dV = this.directionVector,		pV2 = {x: pV1.x - point.x, y: pV1.y - point.y, z: pV1.z - point.z},		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),		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),		x = Math.sqrt(xSq); 	return x;}var v1 = new VectorLine({positionVector: {x: 1, y: 1, z: -3}, directionVector: {x: 2, y: -2, z: -1}});console.log(v1.shortestDistanceToPoint({x: 1, y: 2, z: -1}));`