I am currently working on a keyboard recognition project and creating a simple game in order to demonstrate my understanding of it. When I press the four keys: W, S, A, D, it will print out the direction corresponding to them. (ex. W = Up). A demo down below:
var msg = new SpeechSynthesisUtterance();
var synth = window.speechSynthesis;
function uniKeyCode(event) {
var key = event.which || event.keyCode;
// console.log(key)
if (key == 32 || key == 13) {
document.getElementById("actionCenter").innerHTML = "fire"
msg = new SpeechSynthesisUtterance("fire");
//settings
msg.rate = 1.2; //speech speed - range: 0 to 10
//look into console to see all available voices/languages
msg.voice = synth.getVoices()[0];
//speaking trigger
synth.cancel(); //cut previous voice short
synth.speak(msg);
}
if (key == 87 || key == 38) {
document.getElementById("actionCenter").innerHTML = "jump"
msg = new SpeechSynthesisUtterance("jump");
msg.rate = 1.2;
msg.voice = synth.getVoices()[0];
synth.cancel();
synth.speak(msg);
}
if (key == 83 || key == 40) {
document.getElementById("actionCenter").innerHTML = "roll"
msg = new SpeechSynthesisUtterance("roll");
msg.rate = 1.2;
msg.voice = synth.getVoices()[0];
synth.cancel();
synth.speak(msg);
}
if (key == 65 || key == 37) {
document.getElementById("actionCenter").innerHTML = "roll left"
msg = new SpeechSynthesisUtterance("roll left");
msg.rate = 1.2;
msg.voice = synth.getVoices()[0];
synth.cancel();
synth.speak(msg);
}
if (key == 68 || key == 39) {
document.getElementById("actionCenter").innerHTML = "roll right"
msg = new SpeechSynthesisUtterance("roll right");
msg.rate = 1.2;
msg.voice = synth.getVoices()[0];
synth.cancel();
synth.speak(msg);
}
}
.center {
text-align: center;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="style.css">
<title>Assignment 11a2</title>
</head>
<body onkeydown="uniKeyCode(event)">
<p class="center">Actions
<br>
<span id="actionCenter"></span></p>
<script src="11a2.js"></script>
</body>
</html>
Right now I am trying to make an action for when multiple keys are pressed at the same time(ex. W + A = Jump Left). I tried this:
if (key == 87 && key == 65) {
document.getElementById ("actionCenter").innerHTML = "Jump Left"
}
but apparently, it did not work. The code runs as if those three lines do not exist. What is the problem?