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 across my canvas. What i mean by this is if i press the 'a' and 'd' key, my character moves diagonally to the bottom right. With my current code my character only moves to the right or down.
//client, how i capture my keyboard input.
document.onkeydown = function(event){
console.log(`Keycode: ${event.which}`);
if(event.which == 68 || event.which == 39) //d of pijl rechts
sock.emit('keyPress', 'right');
else if(event.which == 83 || event.which == 40) //s of pijl naar beneden
sock.emit('keyPress','down');
else if(event.which == 65 || event.which == 37) //a of pijl naar links
sock.emit('keyPress','left');
else if(event.which == 87 || event.which == 38) // w of pijl naar omhoog
sock.emit('keyPress','up');
}
//server,
sock.on('keyPress', (keypress) => {
var currentUser = this[sock.id];
if (keypress == 'up') {
currentUser.y = currentUser.y - currentUser.speed;
}
else if (keypress == 'down') {
currentUser.y = currentUser.y + currentUser.speed;
}
else if (keypress == 'left') {
currentUser.x = currentUser.x - currentUser.speed;
}
else if (keypress == 'right') {
currentUser.x = currentUser.x + currentUser.speed;
}
});
setInterval(function(){
io.emit('update-players', Users);
},1000/30);
//client, how all players are drawn onto to canvas
sock.on('update-players', updatePlayers);
var updatePlayers= (Users) => {
ctx.clearRect(0,0,10000,10000);
Users.forEach((user) => {
var img = new Image();
img.src = 'Images/player.png';
ctx.drawImage(img,user.x,user.y,user.width,user.height);
ctx.font = "20px Courier New";
ctx.fillText(`${user.name}`,user.x,(user.y - 10))
}
});
sorry for my crappy english.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…