Andy Fedoroff Andy Fedoroff - 1 month ago 9
Swift Question

Calculating the distance CGPoint travelled from one place to another


What the method do I have to use for calculating the distance that CGPoint travelled from its old position to new position?


var point: CGPoint = CGPointMake(x:50.0, y:50.0)


and there is a method for dragging a point with LMB:

func mouseDragged(event: NSEvent) {

var pointDragged = self.convertPoint(event.locationInWindow, fromView: nil)
}


enter image description here

leo leo
Answer

Use Pythagorean theorem and mouseLocation = event.mouseLocation() where event in your case is of type NSEvent.

let point1: CGPoint = CGPointMake(30.0, 20.0)
let point2: CGPoint = CGPointMake(50.0, 50.0)


let xDist = (point1.x - point2.x)
let yDist = (point1.y - point2.y)
let distance = sqrt((xDist * xDist) + (yDist * yDist))

print(distance)

point1 would be your starting position and you can obtain the position where the user clicked - point2, from the NSEvent in your mouseDragged function:

mouseLocation = event.mouseLocation()
point2 = CGPointMake(mouseLocation.x, mouseLocation.y)
Comments