macOS关键事件慢速重复 [英] macOS Key Event Slow Repeat
问题描述
我正在尝试在macOS中创建一个小型WASD演示游戏.我正在使用NSEvent
来处理关键事件.要检测按键,我正在搜索keyDown
事件.这就是我所拥有的:
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
}
因此,在这里,我按住了按键(就像您在游戏中所期望的那样),并且动作缓慢.就像,当我按住它时,它非常简陋.经过进一步检查,我发现密钥重复间隔为0.1s,这是在我的系统偏好设置中设置的.这意味着它正在跳过帧.但是,在游戏中,我不希望此设置影响运动.那么,如何在按键重复间隔没有阻止的情况下检测按键保持事件 ?
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?
推荐答案
您应该忽略按键重复事件(isARepeat
为true).取而代之的是,当您收到按键事件时,启动一个计时器,该计时器会在您希望提高游戏状态的频率下触发.在该计时器的触发代码中推进游戏状态.当您收到按键事件时,请停止计时器.
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.
这篇关于macOS关键事件慢速重复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!