简体   繁体   English

如何禁用 onkeyup 几秒钟

[英]How to disable onkeyup for a few seconds

im creating a browser game and i have added keybinds so the player can use keys to move around the world.我正在创建一个浏览器游戏,并且我添加了键绑定,以便玩家可以使用键在世界各地移动。 If people use the buttons to move, these buttons are getting hidden for 5 seconds to allow an animation to end.如果人们使用按钮移动,这些按钮会隐藏 5 秒钟以允许动画结束。 Now i want to do this for the keybinds too.现在我也想为键绑定做这个。 For example: Player presses spacebar and a interval will run that lasts 5 seconds.例如:玩家按下空格键,将运行一个持续 5 秒的间隔。 Pressing space again will glitch out really bad running the same interval twice.再次按下空格会在两次相同的间隔中出现非常糟糕的故障。 So how do i disable a function for 5 seconds after it has been called so that it won't glitch out?那么如何在调用函数后将其禁用 5 秒以使其不会出现故障?

This is the code i use for the keys:这是我用于密钥的代码:

<script>
            document.body.onkeyup = function(e){
                if(e.keyCode == 32){
                    var cmd = "<?php echo $row['HEADING']; ?>";
                    if(cmd == "N") myMoveUp();
                    if(cmd == "E") myMoveRight();
                    if(cmd == "S") myMoveDown();
                    if(cmd == "W") myMoveLeft();
                }
                if(e.keyCode == 37){
                    ChangeHeadingKP("W");  
                }
                if(e.keyCode == 38){
                    ChangeHeadingKP("N");  
                }
                if(e.keyCode == 39){
                    ChangeHeadingKP("E");  
                }
                if(e.keyCode == 40){
                    ChangeHeadingKP("S");  
                }
            }
            </script>

Any help would be appreciated.任何帮助,将不胜感激。

I wouldn't rely on timing (say, 5 seconds) because when you change them, you'll have to review your code.我不会依赖时间(比如 5 秒),因为当你改变它们时,你必须检查你的代码。

Instead I'd rely on toggling a flag by calling specific methods, like this:相反,我依赖于通过调用特定方法来切换标志,如下所示:

keymanager.suspend();
// play animation, cutscene or whatever
keymanager.resume();

Those two functions are easy to define, along with the keymanager , as follows:这两个函数以及keymanager很容易定义,如下所示:

var keymanager = {
  "active": true,
  "suspend": () => {
    keymanager.active = false;
  },
  "resume": () => {
    keymanager.active = true;
  }
};

All that remains is the key event handler bailing out when keys are deactivated:剩下的就是在停用键时退出的键事件处理程序:

document.body.onkeyup = function (e) {

  if (!keymanager.active)
  {
    return; // do not process any keys
  }

  // rest of your code...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM