Search code examples
javascripthtmlkeyboarddouble-clickonkeypress

How to Javascript/html5 Input Keyboard in-order set (not in the same time)


I have create a simple game that need to press keyboard buttons exactly follow the step in order to move character. But I cannot figure out how to do it and all I found on the internet is about pressing multiple keyboard buttons in the same time. (set array and use &&)

Picture this: you have to press A then, B, C, and D to move character forward, or D,C,B,andA in-order to move back. All of these are not press at the same time, but follow the set.

So can someone tell me or give me some clue how to do that? Also, what about pressing button like double click mouse?- is it possible.

Thanks in advance.


Solution

  • Just something off the top of my head:

    var aPressed = false;
    var bPressed = false;
    var cPressed = false;
    var dPressed = false;
    
    document.onkeydown = function (event) {
        var key = event.keyCode;
    
        switch (key) {
            case 65:
                aPressed = true;
                break;
            case 66:
                if (aPressed) {
                    bPressed = true;
                }
                break;
            case 67:
                if (aPressed && bPressed) {
                    cPressed = true;
                }
                break;
            case 68:
                if (aPressed && bPressed && cPressed) {
                    dPressed = true;
                }
                break;
            default: //Reset all buttons
                aPressed = false;
                bPressed = false;
                cPressed = false;
                dPressed = false;
                break;
        }
    
        if (dPressed) {
            //Move forward and reset pressed buttons
        }
    }
    

    Hope this can help you a bit :)

    EDIT:

    as for the "double pressing" a button, you could combine it with something like this:

    var presscount = 0;
    var delay = 300;
    
    document.onkeydown = function(){
        presscount++;
    
        if(presscount == 1)
        {
            setTimeout(function(){
                if(presscount == 1)
                {
                    //stuff to do on single press
                }
                else
                {
                    //stuff to do on double press                
                }
            }, delay);   
        }
    }