im trying to create a function that will move an png image either up, down, left or right by the user either pressing WASD or the Arrow Keys. At the moment i have figured out a way to move the item using WASD however when i introduce the "or" operand and use the Key.Code for the arrow keys the arrow keys aren't recognised even though it will still recognise WASD
<body>
<div class="scene">
<div class="rocket">
<img src="rocket.png" alt="" />
</div>
</div>
<script src="script.js"></script>
document.addEventListener("keydown", (e) => {
var rocket = document.querySelector(".rocket");
let speed = 10;
if (event.keyCode == (87 || 38) && rocket.offsetTop > 100) {
rocket.style.top = `${rocket.offsetTop - speed}px`;
}
if (event.key == "s" && rocket.offsetTop < window.innerHeight - 300) {
rocket.style.top = `${rocket.offsetTop + speed}px`;
}
if (event.key == "a" && rocket.offsetLeft > 50) {
rocket.style.left = `${rocket.offsetLeft - speed}px`;
}
if (event.key == "d" && rocket.offsetLeft < window.innerWidth - 125) {
rocket.style.left = `${rocket.offsetLeft + speed}px`;
}
if (event.key == " " && rocket.offsetTop > 100) {
rocket.style.top = `${rocket.offsetTop - 200}px`;
}
console.log(event.keyCode);
});
This expression:
87 || 38
Evaluates to 87. Every time. Which means this expression:
event.keyCode == (87 || 38)
Compares the value to 87. Every time.
Don't think of these logical conditions as intuitive human language. They need to be built as individual logical expressions which individually evaluate to a value. What you're looking for is this:
(event.keyCode == 87 || event.keyCode == 38)
You should try
if ((event.keyCode == 87 || event.keyCode == 38) && rocket.offsetTop > 100)
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_OR