将 AcceptMouseMovedEvents 用于 SpriteKit 鼠标操作以及 Storyboards 和 Swift

Ale*_*ing 1 cocoa iboutlet xcode-storyboard sprite-kit swift

我通过在 Xcode 中使用 Storyboards 引用自定义来创建 SpriteKit 场景NSView。但是,我无法mouseMoved使用 SpriteKit 实现任何事件,因为我不知道如何引用程序NSWindow将其属性设置acceptsMouseMovedEvents为“true”。

如何在我的文件中创建@IBOutlet对 my 的引用,以便更改此属性?NSWindowAppDelegate.swift

0x1*_*41E 6

您可以配置NSTrackingArea对象来跟踪鼠标的移动以及光标进入或退出视图的时间。要创建NSTrackingArea对象,您需要指定要跟踪鼠标事件的视图区域、接收鼠标事件消息的所有者以及跟踪发生的时间(例如,在关键窗口中)。以下是如何向视图添加跟踪区域的示例。添加到您的SKScene子类,例如 GameScene.swift。

斯威夫特 3 和 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)
}
Run Code Online (Sandbox Code Playgroud)

雨燕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)
}
Run Code Online (Sandbox Code Playgroud)