如何暂时停止事件keydown侦听器?

时间:2019-07-17 09:10:45

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

我的问题是:创建新圆圈后,它仍会快速设置动画(减少可变动画效果没有帮助)->如何在发生碰撞后临时杀死keydown事件侦听器,以免影响新圆圈的速度在第一次会话的空格键旁边?

我正在尝试使用canvas和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**
    }
  }
}

2 个答案:

答案 0 :(得分:0)

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

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

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

答案 1 :(得分:0)

您可以添加一个全局布尔变量 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;
    }
  }
}
相关问题