Search code examples
swiftcocoasprite-kitiboutletxcode-storyboard

Using acceptsMouseMovedEvents for SpriteKit mouse actions with Storyboards and Swift


I have created a SpriteKit scene by referencing a custom NSView using Storyboards in Xcode. However, I cannot implement any mouseMoved events using SpriteKit because I do not know how to reference the program's NSWindowto set its acceptsMouseMovedEvents property to "true".

How can I create an @IBOutlet reference to my NSWindow in my AppDelegate.swift file so that I can change this property?


Solution

  • You can configure an NSTrackingArea object to track the movement of the mouse as well as when the cursor enters or exits a view. To create an NSTrackingArea object, you specify a region of a view where you want mouse events to be tracked, the owner that will receive the mouse event messages, and when the tracking will occur (e.g., in the key window). The following is an example of how to add a tracking area to a view. Add to your SKScene subclass, such as GameScene.swift.

    Swift 3 and 4

    override func didMove(to view: SKView) {
        // Create a tracking area object with self as the owner (i.e., the recipient of mouse-tracking messages
        let trackingArea = NSTrackingArea(rect: view.frame, options: [.activeInKeyWindow, .mouseMoved], owner: self, userInfo: nil)
        // Add the tracking area to the view
        view.addTrackingArea(trackingArea)
    }
    
    // This method will be called when the mouse moves in the view
    override func mouseMoved(with theEvent: NSEvent) {
        let location = theEvent.location(in: self)
        print(location)
    }
    

    Swift 2

    override func didMoveToView(view: SKView) {
        // Create a tracking area object with self as the owner (i.e., the recipient of mouse-tracking messages
        let trackingArea = NSTrackingArea(rect: view.frame, options: NSTrackingAreaOptions.ActiveInKeyWindow | NSTrackingAreaOptions.MouseMoved, owner: self, userInfo: nil)
        // Add the tracking area to the view
        view.addTrackingArea(trackingArea)
    }
    
    // This method will be called when the mouse moves in the view
    override func mouseMoved(theEvent: NSEvent) {
        let location = theEvent.locationInNode(self)
        println(location)
    }