macOS Key Event Slow Repeat

社会主义新天地 提交于 2019-12-02 18:37:45

问题


I'm trying to create a small WASD demo game in macOS. I'm using NSEvent for handling the key events. To detect the key presses, I'm searching for keyDown events. Here's what I have:

    NSEvent.addLocalMonitorForEvents(matching: .keyDown) {
        (keyEvent) -> NSEvent? in
        if self.keyDown(with: keyEvent) {
            return nil
        } else {
            return keyEvent
        }
    }

func keyDown(with event: NSEvent) -> Bool {

    userInt.keyDown(key: event.characters)

    return true
}

So here, I'm holding the keys down (as you'd expect in a game), and I'm getting some very slow movement. Like, when I'm holding it down, it's very janky. Upon further inspection, I saw that the key repeat interval was 0.1s, which was set in my system preferences. This means that it's skipping frames. However, in a game, I don't want this setting to affect the movement. So how can I detect a key holding event without being held up by the key repeat interval?


回答1:


You should ignore key-repeat events (with isARepeat true). Instead, when you get a key-down event, start a timer that fires however often you want to advance your game state. Advance the game state in that timer's firing code. When you get a key-up event, stop the timer.



来源:https://stackoverflow.com/questions/51212421/macos-key-event-slow-repeat

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!