我正在编写代码以在浏览器游戏中移动 Angular 色。我设法获得了它每秒必须水平和垂直移动的像素数。
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>
一切正常,直到我不知道如何让它每秒都正常工作。我在这里测试它:http://chusmix.com/game/movechar.php
我如何让它每秒重复一次才能正常工作?
谢谢
最佳答案
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);
}
})();
关于javascript - 每秒重复的简单 Javascript 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5865089/