swift3mousemoveswift-playgroundnstrackingarea

mouseMoved function not called when I move the mouse?


I am trying to find mouse coordinates within an SKScene, however, the moveMouse function is not being called. (This is in a Swift Playground by the way) I even wrote a print function that tested to see if the function was even being called, but it prints absolutely nothing.

This is how I set up my NSTrackingArea:

    let options = [NSTrackingAreaOptions.mouseMoved, NSTrackingAreaOptions.activeInKeyWindow, NSTrackingAreaOptions.activeAlways, NSTrackingAreaOptions.inVisibleRect, ] as NSTrackingAreaOptions
    let tracker = NSTrackingArea(rect: viewFrame, options: options, owner: self.view, userInfo: nil)
    self.view?.addTrackingArea(tracker)

And here is the mouseMoved function (the one that is not being called)

override public func mouseMoved(with event: NSEvent) {

        point = event.location(in: self)
        print(point)
    }

Is there a reason that mouseMoved isn't being called?


Solution

  • I created a playground with the following code (and only that code):

    import AppKit
    import SpriteKit
    import PlaygroundSupport
    
    class Scene:SKScene {
        override public func mouseMoved(with event: NSEvent) {
            let point = event.location(in: self)
            print(point)
        }
    }
    
    let frame = CGRect(x:0, y:0, width:1920, height:1080)
    let view = SKView(frame:frame)
    let scene = Scene(size: CGSize(width: 1080, height: 1080))
    scene.backgroundColor = #colorLiteral(red: 0.4078431373, green: 0.7843137255, blue: 0.6509803922, alpha: 1)
    scene.scaleMode = .aspectFit
    
    let options = [NSTrackingAreaOptions.mouseMoved, NSTrackingAreaOptions.activeInKeyWindow, NSTrackingAreaOptions.activeAlways, NSTrackingAreaOptions.inVisibleRect, ] as NSTrackingAreaOptions
    let tracker = NSTrackingArea(rect:frame, options: options, owner:view, userInfo: nil)
    view.addTrackingArea(tracker)
    
    PlaygroundPage.current.needsIndefiniteExecution = true
    view.presentScene(scene)
    PlaygroundPage.current.liveView = view
    

    Then, I opened the playground Timeline view by clicking the "Show the Assistant Editor" button in the toolbar. I also opened the Debug area so that I could see the console.

    At that point, the Timeline view showed a green view. I moved my mouse pointer over the green view and I could see the mouse coordinates being printed out in the console. So, as far as I can tell, the above code works fine.

    Could you please try the code at your end and see what happens?