简单的Javascript循环,每秒重复一次

lis*_*aro 9 javascript

我正在编写一个代码来移动浏览器游戏中的角色.我设法得到它必须每秒水平和垂直移动的像素.

pxsecx是每秒必须水平移动的像素数pxsecy是相同但垂直的

基本上它应该+ =它们到当前的水平和垂直位置.

我需要循环每秒重复一次,直到元素位置符合新位置(newx).

这就是我已经走了:

<body onmousedown="showCoords(event)">
<script type="text/javascript">
function showCoords(evt){
  oldx = parseInt(document.getElementById("character").style.left);
  oldy = parseInt(document.getElementById("character").style.top);

  width = parseInt(document.getElementById("character").style.width);
  height = parseInt(document.getElementById("character").style.height);

  newx = evt.pageX - width/2;
  newy = evt.pageY - height/2;

  disx = newx - oldx;
  disy = newy - oldy;

  diag = parseInt(Math.sqrt(disx*disx + disy*disy));

  speed = 50;

  secs = diag/speed;

  pxsecx = disx/secs;
  pxsecy = disy/secs;

     while(document.getElementById("character").style.left<newx)
      {
      document.getElementById("character").style.left += pxsecx;
      document.getElementById("character").style.top += pxsecy;
      }
}
</script>
Run Code Online (Sandbox Code Playgroud)

一切都有效,直到我不知道如何让它每秒都有效.我在这里测试它:http://chusmix.com/game/movechar.php

如何让它重复一次,以便它可以工作?

谢谢

ick*_*fay 13

JavaScript主要是异步的,因此您需要稍微重写一下.setTimeout在一定时间后执行一个功能.因此,您可以这样做:

(function move() {
    var character=document.getElementById("character");
    if(character.style.left<newx) {
        character.style.left += pxsecx;
        character.style.top += pxsecy;
        setTimeout(move, 1000);
    }
})();
Run Code Online (Sandbox Code Playgroud)


小智 9

你可以使用这个功能 setInterval(function, interval)

// To start the loop
var mainLoopId = setInterval(function(){
    // Do your update stuff...
    move();
}, 40);

// To stop the loop
clearInterval(mainLoopId);`
Run Code Online (Sandbox Code Playgroud)

  • 间隔(在本例中显示为 40)表示毫秒。 (2认同)