andy - 11 months ago 53

Swift Question

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

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

`func mouseDragged(event: NSEvent) {`

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

}

Answer Source

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)
```