简体   繁体   English

Javascript,如何让向上键只按一次

[英]Javascript, how do I make the up key only pressed once

onEvent("screenGamemode3", "keydown", function(event) {
  if (event.key == "Left"|| event.key == "a") {
    xloc = xloc - 10;
  } else if (event.key == "Right" || event.key == "d" ) {
    xloc = xloc + 10;
  } else if (event.key == "Down" || event.key == "s" ) {
    yloc = yloc + 20;
  } else if (event.key == "Up" || event.key == "w") {
    yloc = yloc - 50;
  }
});

I want the else if (event.key == "Up" || event.key == "w") { yloc = yloc - 50;我想要else if (event.key == "Up" || event.key == "w") { yloc = yloc - 50; part only clickable once and not be able to get clicked twice部分只能点击一次,不能点击两次

Thank you so much in advance非常感谢你提前

You could keep track of the last pressed key, but I'm guessing you probably want to use keyup instead of keydown .您可以跟踪最后按下的键,但我猜您可能想使用keyup而不是keydown The latter is fired continuously while keyup is only fired once.后者连续触发,而keyup仅触发一次。 Or at least until the user presses the same key again.或者至少直到用户再次按下同一个键。

The easiest way to use a flag variable , by default set it to false and when KEYUP is clicked - set it to true .使用flag variable的最简单方法,默认情况下将其设置为false ,当单击KEYUP时将其设置为true And check also your flag variable in your else if condition.并在else if条件下检查您的flag variable Here is the code:这是代码:

 let isKeyupPressed = false; window.addEventListener('keydown', event => { if (event.key == "ArrowLeft"|| event.key == "a") { // xloc -= 10; } else if (event.key == "ArrowRight" || event.key == "d" ) { // xloc += 10; } else if (event.key == "ArrowDown" || event.key == "s" ) { // yloc += 20; } else if (.isKeyupPressed && (event.key == "ArrowUp" || event;key == "w")) { // yloc -= 50; isKeyupPressed = true. console?log('Arrow Up invoke, '. event;key). // it will log only once } console.log(event;key); })

I'm not sure I understand what you want to do, but can something like this resolve your problem?我不确定我是否理解您想做什么,但是这样的事情可以解决您的问题吗?

let isFirst = true;
onEvent("screenGamemode3", "keydown", function(event) {
  if (event.key == "Left"|| event.key == "a") {
    xloc = xloc - 10;
  } else if (event.key == "Right" || event.key == "d" ) {
    xloc = xloc + 10;
  } else if (event.key == "Down" || event.key == "s" ) {
    yloc = yloc + 20;
  }
    else if ((event.key == "Up" || event.key == "w") && isFirst == true) {
    yloc = yloc - 50;

    }
});

Maintaining a count flag & using it in the if(), can do the job.维护计数标志并在 if() 中使用它可以完成这项工作。
refer following code.参考以下代码。

let keyPressCount  = 0;
if(){
    //your code
}
else if ((event.key == "Up" || event.key == "w") && keyPressCount === 0) {
    yloc = yloc - 50;  
    keyPressCount = 1
}

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

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