I have an object moving when i press some keys. It also moves diagonally when I press two keys. The issue is the following:
1) I press 'd', the object goes left.
2) I keep left pressed and I also press 'w'. The object moves diagonally.
3) I release 'w', while 'd' is still pressed. The object stops moving, although 'd' is still down.
How can I fix that?
let keysPressed = ["a", "w", "d", "s"];
const box1 = document.getElementById("box1");
document.addEventListener('keydown', (event) => {
keysPressed[event.key] = true;
var box1x = box1.offsetLeft;
var box1y = box1.offsetTop;
if (keysPressed['d'] && keysPressed['s']) {
box1.style.left = box1x + 20 + 'px';
box1.style.top = box1y + 20 + 'px';
} else if (keysPressed['a'] && keysPressed['s']) {
box1.style.left = box1x - 20 + 'px';
box1.style.top = box1y + 20 + 'px';
} else if (keysPressed['w'] && keysPressed['a']) {
box1.style.left = box1x - 20 + 'px';
box1.style.top = box1y - 20 + 'px';
} else if (keysPressed['w'] && keysPressed['d']) {
box1.style.left = box1x + 20 + 'px';
box1.style.top = box1y - 20 + 'px';
} else if (keysPressed['w']) {
box1.style.top = box1y - 20 + 'px';
} else if (keysPressed['s']) {
box1.style.top = box1y + 20 + 'px';
} else if (keysPressed['a']) {
box1.style.left = box1x - 20 + 'px';
} else if (keysPressed['d']) {
box1.style.left = box1x + 20 + 'px';
}
});
Aucun commentaire:
Enregistrer un commentaire