I can’t make the image with id yoshi move around my 2d game
document.onkeydown = (e) => {
if (e.keyCode == 37) yoshi.style.left = yoshi.offsetLeft - 5 + "px";
else if (e.keyCode == 38) yoshi.style.top = yoshi.offsetTop - 5 + "px";
else if (e.keyCode == 39) yoshi.style.left = yoshi.offsetLeft + 5 + "px";
else if (e.keyCode == 40) yoshi.style.top = yoshi.offsetTop + 5 + "px";
};
#yoshi {
position: relative;
width: 80px;
height: 80px;
left: 4px;
top: 4px;
}
<body>
<div id="quarto">
<img src="assents/image/yoshi.png" alt="yoshi" id="yoshi" />
</div>
</body>
The right and down movement is normal, but when I press the up and left keys, yoshi keeps walking down and right, respectively
2
Answers
Mixing
style
andoffsetTop
/offsetLeft
is difficult. UsegetComputedStyle
if you don’t want to set the initial values oftop
andleft
in HTML (inline CSS). If you don’t mind inline CSS, replacegetComputedStyle(yoshi)
withyoshi.style
.Alternatively to the good answer by @haolt:
Don’t rely on the styles to store the position. Instead store the position yourself. For example: