如何在 Dart 游戏中重复听按键? [英] How to listen to key press repetitively in Dart for games?

查看:17
本文介绍了如何在 Dart 游戏中重复听按键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道你可以使用 Dart 监听按键按下和按下事件,例如:

I know that you can listen to key press and down events with Dart like:

var el = query('#el');
el.on.keyDown.add((e) {});

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

But the problem here is that it fires only once. I want repetition.

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

So, I tried keyPress instead, but it has a slight delay before the repetition. I am working on a game and I want it to fire instantly and repetitively.

推荐答案

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

First of all, don't listen to keyPress events, because the "initial delay" depends on the operating system configuration! In fact, keyPress events may not even fire repetitively.

你需要做的是监听 keyDownkeyUp 事件.你可以为此做一个助手.

What you need to do is to listen to keyDown and keyUp events. You can make a helper for this.

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);
}

然后根据你在游戏中所做的事情,你可能有某种游戏循环",在你的 update() 方法中,每隔一段时间就会被调用一次:

Then depending on what you do in your game, you probably have "a game loop" of some sort, in your update() method that gets called in every once in a while:

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);
  }
}

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

Now your game loop checks repetitively for A key pressing.

这篇关于如何在 Dart 游戏中重复听按键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆