我正在玩动画。我试图让两个圆圈移动指定的距离然后停止。我遇到的问题是多个间隔。我将每个间隔分配给一个唯一的变量,并清除该变量,但第一个间隔继续。
这是代码:
function moveRight(player){
if(player==1){
currentLoc = p1Loc[0]; //global var with player's current location
intervalR1 = setInterval(function(){
p1Loc[0]+=1;
draw(); //function that redraws the canvas
if(p1Loc[0]>currentLoc+wu){ //wu is a single "width-unit"
clearInterval(intervalR1);
}
},5)
}
else{
currentLoc = p2Loc[0];
intervalR2 = setInterval(function(){
p2Loc[0]+=1;
draw();
if(p2Loc[0]>currentLoc+wu){
clearInterval(intervalR2);
}
},5)
}
}
然后,假设我在 while 循环内给出以下指令:
instructions = ["moveRight(1)", "moveRight(2)"];
for(instruction in instructions){
eval(instructions[instruction]); //I know, eval(), ugh. Is just temporary
}
最终发生的情况是,两个玩家都开始向右移动,但玩家 2 在一个 wu(或宽度单位)后停止,而玩家 1 继续前进。如果我将指令更改为仅“moveRight(1);”,那么玩家一会移动一个 wu 并停止。
这是怎么回事?
最佳答案
这只是一个猜测,因为很难仅用部分代码来判断发生了什么,但是是否可能您分配了 currnetLoc
两次,因此第一个玩家的位置总是会与 p2Loc[0]
进行比较?
因此,当您调用 moveRight(1)
时,它将 currentLoc
设置为 p1Loc[0]
,然后继续。然后,在调用 moveRight(2)
后立即将 currentLoc
设置为 p2Loc[0]
。因此,现在玩家 1 的间隔比较不再是 p1Loc[0]>currentLoc+wu
,而是 p2Loc[0]>currentLoc+wu
。根据 p2Loc
的值,这可能始终为 false
。
关于JavaScript setInterval : multiple intervals,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27726118/