簡體   English   中英

為什么 splice 從數組中刪除所有元素?

[英]Why is splice removing all the elements from an array?

所以我正在嘗試制作這款游戲(我在視頻中看到過),但我想以不同的方式制作它,但我被卡住了。 我有這個帶有射彈的陣列。 基本上,每次彈丸移出屏幕時,我都想從陣列中刪除該彈丸。 問題是當彈丸擊中屏幕時,所有彈丸都被刪除了。

編碼:

function animate(){

    requestAnimationFrame(animate);
    c.clearRect(0, 0, width, height);
    player.draw();
    
    //shoot on click
    addEventListener('click', function(event){
        mousex = event.clientX;
        mousey = event.clientY;
        let angle = Math.atan2(mousey - player.y, mousex - player.x);
        projectiledx = Math.cos(angle) * 8;
        projectiledy = Math.sin(angle) * 8; 
        projectileArray.push(new Projectile(width/2, height/2, 10, projectiledx, projectiledy, black));

    })
    for(let i = 0; i < projectileArray.length; i++){
        projectileArray[i].update();
        if(projectileArray[i].x + projectileArray[i].radius < 0 || projectileArray[i].x - projectileArray[i].radius >= width){
            projectileArray[i].splice(i, 1);
         }
         if(projectileArray[i].y + projectileArray[i].radius < 0 || projectileArray[i].y - projectileArray[i].radius >= height){
            projectileArray[i].splice(i, 1);
         }
    }
}
animate();

我在這里至少可以看到兩個問題:

  1. .splice之前不應該有[i]

  2. 您正在使用 for 循環迭代數組,並且在該循環中您想修改該數組的長度 - 這對我來說似乎是個壞主意。最好獲取要刪除的項目列表,然后在該循環之后...刪除它們(從最后一個開始)在另一個循環中,如下所示:

     var removalList = []; for(let i = 0; i < projectileArray.length; i++){ projectileArray[i].update(); if( projectileArray[i].x + projectileArray[i].radius < 0 || projectileArray[i].x - projectileArray[i].radius >= width || projectileArray[i].y + projectileArray[i].radius < 0 || projectileArray[i].y - projectileArray[i].radius >= height ){ removalList.push(i); } } for(let i=removalList.length; i>0; i--){ projectileArray.splice( removalList[i-1], 1 ); }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM