macoskeyboardnseventmacos-high-sierra

macOS Key Event Slow Repeat


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?


Solution

  • 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.