Skip to content

Instantly share code, notes, and snippets.

@johnwheeler
Created December 28, 2015 17:37
Show Gist options
  • Save johnwheeler/b1b8ee8951ef19c2fe4f to your computer and use it in GitHub Desktop.
Save johnwheeler/b1b8ee8951ef19c2fe4f to your computer and use it in GitHub Desktop.
distance to point
func distanceToPoint(point p: CGPoint, fromLineSegmentBetween l1: CGPoint, and l2: CGPoint) -> Float {
let a = p.x - l1.x
let b = p.y - l1.y
let c = l2.x - l1.x
let d = l2.y - l1.y
let dot = a * c + b * d
let lenSq = c * c + d * d
let param = dot / lenSq
var xx:CGFloat!
var yy:CGFloat!
if param < 0 || (l1.x == l2.x && l1.y == l2.y) {
xx = l1.x
yy = l1.y
} else if (param > 1) {
xx = l2.x
yy = l2.y
} else {
xx = l1.x + param * c
yy = l1.y + param * d
}
let dx = Float(p.x - xx)
let dy = Float(p.y - yy)
return sqrtf(dx * dx + dy * dy)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment