vendredi 1 octobre 2021

JS returning true for every key using on key down

I have this some javascript code that im using to check if a certain key is pressed, and then if the key set is pressed then it sets its assigned variable to true there are four set keys. But when I run the code when the first key is pressed no matter what key it is it sets everything to false, but the next time I click no matter what key all the variables are then true, and they all remain true the rest of the time the code is running. Heres my code.

document.addEventListener("keydown", function(e) {
console.log("pressed key")
console.log(event.KeyCode)

if(e.key == " " || e.key == "Enter"){/select that option/}
if(e.key == 'ArrowUp'){keyW=true}
if(e.key == 'ArrowLeft'){keyA=true}
if(e.key == 'ArrowDown'){keyS=true}
if(e.key == 'ArrowRight'){keyD=true}
    
console.log(keyW)
console.log(keyA)
console.log(keyS)
console.log(keyD)

if(keyW=true){
  click_sound.play();
  console.log("Pressed up arrow")
}
if(keyA=true){
  click_sound.play();
  console.log("Pressed left arrow")
}
if(keyS=true){
  click_sound.play();
  console.log("Pressed down arrow")
}
if(keyD=true){
  click_sound.play();
  console.log("Pressed right arrow")
}
});

Does anyone know whats wrong? I can't figure it out. I've tried using different ways to check what key was pressed and everything, and all I keep getting is errors. Thanks in advanced.




Aucun commentaire:

Enregistrer un commentaire