Skip to content

Instantly share code, notes, and snippets.

@bobbzorzen
Created September 10, 2018 12:33
Show Gist options
  • Save bobbzorzen/b03fab8f323f85254da093ede634388b to your computer and use it in GitHub Desktop.
Save bobbzorzen/b03fab8f323f85254da093ede634388b to your computer and use it in GitHub Desktop.
Find a point on a line given a distance from a known point on the line
public findDistanceBetweenPoints(pointA, pointB) {
var a = pointA["x"] - pointB["x"]
var b = pointA["y"] - pointB["y"]
var length = Math.sqrt(a*a + b*b)
return length
}
public findSlope(pointA, pointB) {
var a = pointB["y"] - pointA["y"]
var b = pointB["x"] - pointA["x"]
var m = a / b
return m
}
public findUnitLengthVector(slope) {
var mSquared = slope**2
var unitLengthVector = Math.sqrt(1+mSquared)
return unitLengthVector
}
public findClosestPoint(point1, point2, targetPoint) {
var distance1 = this.findDistanceBetweenPoints(point1, targetPoint)
var distance2 = this.findDistanceBetweenPoints(point2, targetPoint)
if(distance1 < distance2){
return point1
}
return point2
}
public findMissingCoordinate(pointA, pointB, distance){
var slope = this.findSlope(pointA, pointB)
var unitLengthVector = this.findUnitLengthVector(slope)
var x1 = (pointA["x"] - (distance/unitLengthVector))
var y1 = (pointA["y"] - (distance/unitLengthVector))
var x2 = (pointA["x"] + (distance/unitLengthVector))
var y2 = (pointA["y"] + (distance/unitLengthVector))
var point1 = {"x": x1, "y": y1}
var point2 = {"x": x2, "y": y2}
return this.findClosestPoint(point1, point2, pointB)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment