【问题标题】:how to stop event keydown listener temporary?如何暂时停止事件keydown监听器?
【发布时间】:2019-11-26 01:57:54
【问题描述】:

我的问题是:新圆创建后,动画仍然很快(减少变量动画没有帮助)-> 碰撞发生后如何临时杀死keydown事件监听器,从而无法影响新圆的速度通过第一个会话的空格键?

我正在尝试使用画布和 javascript 制作简单的 game2d。

由于按下空格键,圆圈应该移动得更快(增加动画函数的变量)。 但如果与墙发生碰撞,则应该是游戏结束,那么应该创建新的圆圈。这实际上正在发生。

move(event) {
  if (event.keyCode === 65 ) { //left
    this.cir.x -= 1 
  } else if (event.keyCode === 68 ) { //right
    this.cir.x += 1
  } else if (event.keyCode === 83 ) { //down
    if(cir.coll){
      this.cir = new cir(1,0);
    } 
    this.cir.x+= 1
  } else if (event.key == ' ' ) { // spacebar button
    this.dropInterval = 1 
    if(cir.coll){
      this.cir = new cir(1,0) **// for new circle spacebar keydown should be killed temporary so that i should press it again for the new object**
    }
  }
}

【问题讨论】:

    标签: javascript html node.js animation 2d-games


    【解决方案1】:

    如果您只想停止触发空格键 keydown 事件,您可以尝试创建一个布尔值,如“canPressSpace”,当圆圈与墙壁碰撞时,您调用一个函数在有限的时间内将此布尔值设置为 false或直到某些其他事件重新触发它。

    在空格键按下事件时,只需添加if (canPressSpace) 验证即可。

    我不确定这是否会解决您的动画问题,但它应该会暂时停止空格键 keydown 事件功能。

    【讨论】:

      【解决方案2】:

      您可以添加一个全局布尔变量deactivated,在执行按空格键时应运行的代码之前检查该变量。如果创建了一个新圈子,请将其设置为 true。要重置此变量,您可以添加一个 keyUp 事件侦听器,该事件侦听器会在释放键后立即触发 - 在您的情况下为空格键。

      例如

      var deactivated = false;
      
      window.addEventListener("keyup", function(event) {
        if (event.key == " ") {
          deactivated = false;
        }
      });
      
      function move(event) {
        if (event.keyCode === 65) { //left
          this.cir.x -= 1
        } else if (event.keyCode === 68) { //right
          this.cir.x += 1
        } else if (event.keyCode === 83) { //down
          if (cir.coll) {
            this.cir = new cir(1, 0);
          }
          this.cir.x += 1
        } else if (event.key == ' ' && !deactivated) { // spacebar button
          this.dropInterval = 1
          if (cir.coll) {
            this.cir = new cir(1, 0);
            deactivated = true;
          }
        }
      }
      

      【讨论】:

      • 我需要的是在创建新的 cir 后强制玩家再次单击空格键。
      • 我完善了答案!
      猜你喜欢
      • 2023-03-14
      • 2012-05-24
      • 1970-01-01
      • 2016-01-07
      • 2023-02-07
      • 2012-08-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多