为什么拼接从数组中删除所有元素? [英] Why is splice removing all the elements from an array?

查看:57
本文介绍了为什么拼接从数组中删除所有元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我试图制作这个游戏(我已经在视频中看到过),但是我想做出不同的选择,所以我被困住了.我有这个带有弹丸的阵列.基本上,每次弹丸移出屏幕时,我都希望从阵列中删除该弹丸.问题是当弹丸击中屏幕时,所有弹丸都将被删除.

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.

代码:

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. .splice

您正在使用for循环迭代数组,而在该循环中您想修改该数组的长度-对我来说这似乎是个坏主意.最好列出要删除的项目列表,然后在该循​​环之后...在另一个循环中将它们(从最后一个开始)删除,如下所示:

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

这篇关于为什么拼接从数组中删除所有元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆