简体   繁体   中英

Why is splice removing all the elements from an array?

So I am trying to make this game(which I've seen in a video), but I'd like to make it differently, and I am stuck. I have this array with projectiles. Basically, every time a projectile moves out of the screen I'd like to delete that projectile from the array. The problem is when the projectile hits the screen all of the projectiles are being deleted.

The code:

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();

I can see at least two problems here:

  1. there should not be [i] before .splice

  2. You are iterating the array with for loop and whithin that loop you want to modify the length of that array - it looks like a bad idea to me.. Better take a list of items to remove and after that loop...remove them (begining from the last) in another loop like this:

     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 ); }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM