How to handle multi key press for game purposes in jquery/javascript?

前端 未结 1 1587
太阳男子
太阳男子 2021-01-26 12:27

I\'m trying to do a multi-key press combination validation for a \"little game\" test im doing. Basically is a character from Mortal Kombat which I move with ASDW keys... but wh

1条回答
  •  温柔的废话
    2021-01-26 13:12

    You don't necessarily need to rely on jQuery for capturing the keys.

    Here is a plain javascript solution

    var keys = [];
    document.body.innerHTML = "Keys currently pressed: "
    window.addEventListener("keydown",
      function(e){
        keys[e.keyCode] = e.keyCode;
        var keysArray = getNumberArray(keys);
        document.body.innerHTML = "Keys currently pressed:" + keysArray;
        if(keysArray.toString() == "17,65"){
          document.body.innerHTML += " Select all!"
        }
      },
      false);
    
    window.addEventListener('keyup',
      function(e){
        keys[e.keyCode] = false;
        document.body.innerHTML = "Keys currently pressed: " + getNumberArray(keys);
      },
      false);
    
    function getNumberArray(arr){
      var newArr = new Array();
      for(var i = 0; i < arr.length; i++){
        if(typeof arr[i] == "number"){
          newArr[newArr.length] = arr[i];
        }
      }
      return newArr;
    }
    

    As you can see, detecting multiple keypresses and releases at the same time is not a problem, technically speaking.

    I think the only browser culprit here (for plain JS) is e.keyCode. If you want to use jQuery you can rewrite the listener definitions so that they use jQuery.

    In this question i asked for a proper but plain image preloader.

    See the answer supplied; you can use this code to handle the preloading properly.

    Hope that helps!

    0 讨论(0)
提交回复
热议问题