skip to Main Content

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


  1. Mixing style and offsetTop/offsetLeft is difficult. Use getComputedStyle if you don’t want to set the initial values of top and left in HTML (inline CSS). If you don’t mind inline CSS, replace getComputedStyle(yoshi) with yoshi.style.

    document.onkeydown = (e) => {
      if (e.keyCode == 37) yoshi.style.left = parseInt(getComputedStyle(yoshi).left) - 5 + "px";
      else if (e.keyCode == 38) yoshi.style.top = parseInt(getComputedStyle(yoshi).top) - 5 + "px";
      else if (e.keyCode == 39) yoshi.style.left = parseInt(getComputedStyle(yoshi).left) + 5 + "px";
      else if (e.keyCode == 40) yoshi.style.top = parseInt(getComputedStyle(yoshi).top) + 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>
    Login or Signup to reply.
  2. Alternatively to the good answer by @haolt:

    Don’t rely on the styles to store the position. Instead store the position yourself. For example:

    const yoshiPosition = {top: 0, left: 0};
    
    document.onkeydown = (e) => {
      if (e.keyCode == 37) yoshiPosition.left += 5;
      else if (e.keyCode == 38) yoshiPosition.top -= 5;
      else if (e.keyCode == 39) yoshiPosition.left -= 5;
      else if (e.keyCode == 40) yoshiPosition.top += 5;
    
      yoshi.style.top = yoshiPosition.top + "px";
      yoshi.style.left = yoshiPosition.left + "px";
    };
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search