mardi 16 juin 2020

How to fix this if statement

I have an object which I want to move diagonally when pressing two keys. So far it works, but after releasing the two keys, if I press just one key, namely 's', it keeps moving diagonally. How can I get the object move diagonally ONLY when pressing the two keys together?

let keysPressed = ["d", "s"];
const box1 = document.getElementById("box1");
var box1x = box1.offsetLeft;
var box1y = box1.offsetHeight;

document.addEventListener('keydown', (event) => {
keysPressed[event.key] = true;
if (keysPressed['d'] && event.key == 's') {
   box1.style.left = document.getElementById("box1").offsetLeft + 5 + 'px';
   box1.style.top = document.getElementById("box1").offsetTop + 5 + 'px';
} 
});

Aucun commentaire:

Enregistrer un commentaire