While using visual studio code, I noticed that I can move a car forwards and backwards with the arrow keys on the keyboard. However, it doesn't seem to turn when I try to move in opposite directions. Is there a way to achieve this through animation? Additionally, I encountered an issue where the movement didn't work within a code snippet, although it functions properly in my visual studio code environment.
var bodyEl = document.querySelector("body");
var boxEl = document.querySelector("div");
var left = 0;
var top = 180;
var speed = 10;
bodyEl.addEventListener ("keydown", moveBox);
function moveBox(e) {
if (e.keyCode === 37) {
left -= speed;
}
else if (e.keyCode === 39) {
left += speed;
}
else if (e.keyCode === 38) {
top -= speed;
}
else if (e.keyCode === 40) {
top += speed;
}
boxEl.style.top = top + "px";
boxEl.style.left = left + "px";
}
body {
background-image: url("https://i.stack.imgur.com/x1iaz.jpg");
cursor: none;
overflow: hidden;
}
div {
position: absolute;
top: 180px;
}
<div><img src="https://i.stack.imgur.com/9dPYr.png" height="300px" width="300px" ></div>