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

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

问题描述

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

但这里的问题是它只发出一次。我想重复。



所以,我尝试了 keyPress ,但它有一个轻微的延迟之前的重复。

解决方案

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



您需要做的是听< c $ c> keyDown 和 keyUp 事件。

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

Keyboard(){
window.onKeyDown.listen((KeyboardEvent e){
//如果尚未设置键,请使用时间戳设置
if(!_keys.containsKey(e.keyCode))
_keys [e.keyCode] = e.timeStamp;
});

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

/ **
*检查给定的键代码是否被按下。您应该使用[KeyCode]类。
* /
isPressed(int keyCode)=> _keys.containsKey(keyCode);
}

然后根据你在游戏中做什么,你可能有在 update()方法中每次调用一次:

  class Game {
键盘键盘;

Game(){
keyboard = new Keyboard();

window.requestAnimationFrame(update);
}

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

window.requestAnimationFrame(update);
}
}

现在你的游戏循环重复检查 A 键。


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.

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.

解决方案

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.

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

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

Now your game loop checks repetitively for A key pressing.

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

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