macosswift2mouseeventcgpoint

Calculating the distance CGPoint travelled from one place to another


What 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)
}

Solution

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

    let point1: CGPoint = CGPoint(x: 2.0, y: 9.0)
    let point2: CGPoint = CGPoint(x: 4.0, y: 13.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)