Search code examples
javascriptmovekeydownkeyup

Move object diagonally with keydown and keyup events, Javascript


Hi Im struggling with keyup and keydown events and my effort is to make object on screen move diagonally afer pressing at the same time keys "s" and "d" or "a" and "w" etc. I read lot of topics about this with no conclusion for me.

This is what Ive got so far:

    window.addEventListener("keydown", keysPressed, false);
    window.addEventListener("keyup", keysReleased, false);
         
        var keys = [];
         
        function keysPressed(e) {
            
            keys[e.keyCode] = true;
            var oldLeft = getComputedStyle(document.body).left,
                    newLeft;
            var oldTop = getComputedStyle(document.body).top,
                newTop;

            oldLeft = parseInt(oldLeft);
            oldTop = parseInt(oldTop);
             
            
            if (keys[65]) {
                newLeft = oldLeft - 10;
            }
             
            else if (keys[68]) {
                newLeft = oldLeft + 10;
            }

            else if (keys[87]) {
                newTop = oldTop - 10;
            }

            else if (keys[83]) {
                newTop = oldTop + 10;
            }
            
            document.body.style.left = newLeft + 'px';
            document.body.style.top = newTop + 'px';
               
            e.preventDefault();
         }

         
        function keysReleased(e) {
            keys[e.keyCode] = false;
         }

I know there is tons of similar questions out there and i saw a lot of them but still cant uderstand how it works.


Solution

  • You need to remove the else in else if (keys[87]) {, with your current code you are not checking for up/down if left or right is pressed.

    Note: I didn't check the keycodes, but I assume they correspond to the keys you want.