在Swift中使用SceneKit游戏的箭头键输入

时间:2015-08-07 15:52:04

标签: swift scenekit nsevent

我正在尝试创建一个swift文件,它将检测来自MacOS的键盘输入,以便在swift中进行SceneKit游戏。我正在使用NSEvent来处理关键事件,但我不断收到错误'使用未声明的类型NSEvent。有没有更简单的方法来实现这一目标?

我尝试过以下代码:

override func keyDown(event: NSEvent) {
    interpretKeyEvents([event]) // calls insertText(_:), moveUp(_:), etc.
}

override func insertText(insertString: AnyObject) {
    let str = insertString as! String
    switch str {
    case " ":
        println("User hit the spacebar.")
    default:
        println("Unrecognized input: \(str)")
    }
}

override func moveUp(sender: AnyObject?) {
    println("Up arrow.")
}

override func moveLeft(sender: AnyObject?) {
    println("Left arrow.")
}

override func deleteBackward(sender: AnyObject?) {
    println("Delete.")
}

2 个答案:

答案 0 :(得分:2)

这将有效:

override func keyDown(theEvent: NSEvent) {
    let keyCode = theEvent.keyCode if(keyCode == 123)//Left{
    }
    if(keyCode == 124)//Right
    {
    }
    if(keyCode == 125)//Down
    {
    }
    if(keyCode == 126)//Up
    {
    }

答案 1 :(得分:0)

这是对(2015)进行质量检查的更新(2020)。

override func pressesBegan(_ presses: Set<UIPress>, with event: UIPressesEvent?) {
guard let key = presses.first?.key else { return }

switch key.keyCode {
case .keyboardR:
    print("Roll dice")
case .keyboardH:
    print("Show help")
default:
    super.pressesBegan(presses, with: event)
}

}