如何在Dart游戏中重复听按键?

Tow*_*wer 10 keyboard keypress dart

我知道您可以通过Dart收听按键和按键事件:

var el = query('#el');
el.on.keyDown.add((e) {});
Run Code Online (Sandbox Code Playgroud)

但这里的问题是它只发射一次.我想重复一遍.

所以,我尝试了keyPress,但在重复之前有一点延迟.我正在开发一款游戏,我希望它可以立即重复发射.

Kai*_*ren 23

首先,不要听keyPress事件,因为"初始延迟"取决于操作系统配置!事实上,keyPress事件甚至可能不会重复发生.

你需要做的是倾听keyDownkeyUp发生事件.你可以为此做一个帮手.

class Keyboard {
  HashMap<int, int> _keys = new HashMap<int, int>();

  Keyboard() {
    window.onKeyDown.listen((KeyboardEvent e) {
      // If the key is not set yet, set it with a timestamp.
      if (!_keys.containsKey(e.keyCode))
        _keys[e.keyCode] = e.timeStamp;
    });

    window.onKeyUp.listen((KeyboardEvent e) {
      _keys.remove(e.keyCode);
    });
  }

  /**
   * Check if the given key code is pressed. You should use the [KeyCode] class.
   */
  isPressed(int keyCode) => _keys.containsKey(keyCode);
}
Run Code Online (Sandbox Code Playgroud)

然后根据你在游戏中做的事情,你可能会在你的update()方法中有某种"游戏循环",偶尔会被调用:

class Game {
  Keyboard keyboard;

  Game() {
    keyboard = new Keyboard();

    window.requestAnimationFrame(update);
  }

  update(e) {
    if (keyboard.isPressed(KeyCode.A))
      print('A is pressed!');

    window.requestAnimationFrame(update);
  }
}
Run Code Online (Sandbox Code Playgroud)

现在你的游戏循环会重复检查A按键.