Created
October 21, 2017 17:36
-
-
Save 50percentgrey/dbb9d19d5ab938be7b01d20875606171 to your computer and use it in GitHub Desktop.
Math series: Distance between 2 points
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Pythagorean theorem | |
// √(x1 - x2)2 + (y1 - y2)2 | |
// | |
extension CGPoint { | |
func distance(from point: CGPoint) -> CGFloat { | |
let xDist = point.x - x | |
let yDist = point.y - y | |
return sqrt((xDist * xDist) + (yDist * yDist)) | |
} | |
} | |
// or calculating the hypotenuse | |
extension CGPoint { | |
func distance(from point: CGPoint) -> CGFloat { | |
return hypot(x - point.x, y - point.y) | |
} | |
} | |
// usage | |
let distance: CGFloat = pointA.distance(from: pointB) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment