如何从游戏循环内的数组中删除对象 (setInterval)



>我有一个单击事件,它检查数组中的对象是否应该被删除(isSquished(,当它是真的时,我们从数组列表中删除该对象,但是当这种情况出现时,我要么需要脱离循环,要么递减i值,基本上我想从for循环中出来,并在拼接数组对象后使用newArray列表长度再次调用gameloop。

我尝试了两种方式

  1. 向后迭代 for 循环
  2. 给出中断声明
  3. (获取非法中断声明( 但这对我来说仍然没有发生,所以有人可以帮助我解决这个问题,让我知道我如何解决这个问题,

    maingameloop = function(antsArray) {
    //inititialization
    // antsArray[i].draw();
    // antsArray[i].checkifSmashed();
    //gameloop
    if (this.isplaying) {
    console.log(this.score);
    for (let i = 0; i < antsArray.length; i++) {
    let gameloop = setInterval(() => {
    antsArray[i].move();
    antsArray[i].update(antsArray);
    if (antsArray[i].isSquashed) {
    this.score++;
    antsArray.splice(i, 1);
    // i--;
    clearInterval(gameloop);
    // this.isplaying = false ;
    }
    },
    this.FRAME_RATE,
    );
    }
    } else {
    //gameover
    // this.maingameloop(antsArray);
    }
    }
    

当我从数组中删除对象时,我得到的 o/p 是:

Uncaught TypeError: Cannot read property 'move' of undefined

循环间隔或超时从来都不是一个好主意

试试这个

var cnt = antsArray.length
function ants() {
if (cnt <= 0) {
//gameover
// this.maingameloop(antsArray);
return;
}
if (this.isplaying) {
console.log(this.score);
antsArray[cnt].move();
antsArray[cnt].update(antsArray); // ???
if (antsArray[cnt].isSquashed) {
this.score++;
cnt--;
}
setTimeout(play, this.FRAME_RATE);
}
}

避免在循环中运行 setInterval,因为它需要异步回调才能在同步循环中运行,同步循环将始终显示此类错误。

我清除了 setInterval,然后我检查了条件并添加了一个中断,这不会是非法的,因为我超出了间隔,所以它为我解决了,谢谢大家的建议

maingameloop = function (antsArray( {

//inititialization
// antsArray[i].draw();
// antsArray[i].checkifSmashed();
//gameloop
if (this.isplaying) {
for (let i = 0; i< antsArray.length;  i++) {
let gameloop = setInterval(() => {
antsArray[i].move();
antsArray[i].update(antsArray);
if (antsArray[i].isSquashed) {
this.score++;                             
clearInterval(gameloop);           
}
}  
, this.FRAME_RATE);
if(antsArray[i].isSquashed ){
antsArray.splice(i, 1);
break;
}  
}
}else {
//gameover
// this.maingameloop(antsArray);
}
}

最新更新