按下多个键,但只需要触发某些键,直到在JavaScript中被按下为止

时间:2019-02-22 00:52:23

标签: javascript

我正在使用W3Schools(https://www.w3schools.com/graphics/game_controllers.asp)上的多键方法。 我只需要按下某些键一次,直到按下它们,即88和90(X和Z)即可。

代码:

var keys = []; // Array of keys
onkeydown = onkeyup = function(e) {
    e = e || event; // to deal with IE
    keys[e.keyCode] = e.type == 'keydown';
}

function keyInputs() {

    if (x > 0 - (offsetXright[piece][rotation] * 20) && keys[37]) {
        x -= 20
    } //Left key

    if (x < 180 + (offsetXleft[piece][rotation] * 20) && keys[39]) {
        x += 20
    } //Right key

    if (keys[40]) {
        y += 20;
    } //Down key

    if (keys[90]) {
        rotation -= 1;
    } //Z key

    if (keys[88]) {
        rotation += 1;
    } //X key 
}

1 个答案:

答案 0 :(得分:0)

问题是,只要您按住键,就会触发keyDown处理程序。 我建议添加一个全局变量 released ,一旦发布z或x,就将其设置为true。 现在,您可以简单地检查是否按下 z ,如果 released == true ,则按下-旋转对象并将其释放设置为false。

这里是一个示例:

    var canvas = document.createElement("canvas");
    canvas.width = 400;
    canvas.height = 300;
    var context = canvas.getContext("2d");
    document.body.appendChild(canvas);
    var player = {
      xPos: 110,
      yPos: 110,
      rotation: 0,
      width: 24,
      height: 24
    };
    var keys = [];
    var released = true;
    window.addEventListener('keydown', function(e) {
      keys = (keys || []);
      keys[e.keyCode] = true;
    });
    window.addEventListener('keyup', function(e) {
      keys[e.keyCode] = false;
      if (e.keyCode == 88 || e.keyCode == 90) {
        released = true;
      }
    });


    function loop() {
      if (keys[37]) {
        player.xPos -= 10;
      }
      if (keys[39]) {
        player.xPos += 10;
      }
      if (keys[90] && released) {
        player.rotation--;
        released = false;
      }
      if (keys[88] && released) {
        player.rotation++;
        released = false;
      }
      context.clearRect(0, 0, canvas.width, canvas.height);
      context.fillStyle = "red";
      context.save();
      context.rotate(player.rotation * Math.PI / 180);
      context.fillRect(player.xPos, player.yPos, player.width, player.height);
      context.restore();
    }
    var interval = setInterval(loop, 20);