Skip to content Skip to sidebar Skip to footer

Player Movement In Javascript With Socket.io

Im currently making a html5 multiplayer game with socket.io. My problem is that i can only move my character in a straight line, while i also want to be able to move diagonal acros

Solution 1:

When we press two keys on the keyboard and hold them down, only the last key pressed gets repeated events in the keydown listener. So, for example, if you press DOWN and RIGHT "at the same time", only one will be repeatedly reported to the listener and the other will be ignored.

A better approach is to have listeners for the keydown and keydown events, like this:

var keyStates = {
    up: false,
    down: false,
    left: false,
    right: false
}

functionupdateKeyStates(code, value) {
    if(code == 68 || code == 39)   //d of pijl rechts
        keyStates.right = value;
    elseif(code == 83 || code == 40)  //s of pijl naar beneden
        keyStates.down = value;
    elseif(code == 65 || code == 37) //a of pijl naar  links
        keyStates.left = value;
    elseif(code == 87 || code == 38) // w of pijl naar omhoog
        keyStates.up = value;
}

document.addEventListener('keydown', function(event) {
    console.log(`Pressed: ${event.which}`); 
    updateKeyStates(event.which, true);
});

document.addEventListener('keyup', function(event) {
    console.log(`Released: ${event.which}`);
    updateKeyStates(event.which, false);
});

So we basically have a boolean variable for each direction. You should send that information (keyStates) to the server and it should do the math based on which keys are down.

Post a Comment for "Player Movement In Javascript With Socket.io"