Search code examples
actionscript-3actionscriptflash-cs6

AS3: Vector item isn't spliced


Hello I am creating a system with a gun that shoots bullet.

The update function is processed this way:

        var b:Bullet;
        var l:uint = bulletList.length;
        var i:uint;

        for (i = 0; i < l; i++) {
            b = bulletList[i];
            b.sprite.x +=  b.vx;
            b.sprite.y +=  b.vy;

            if (b.sprite.x > 1200 || b.sprite.x < -100 || b.sprite.y < -1000) {
                deleteBullet(b);
                bulletList.splice(i,1);
            }

        }

    public function deleteBullet(b:Bullet) {
        b.sprite = null;
        b = null;
    }

When I shoot a bullet and it goes of the edge it generates an error, and sometimes it creates a new one but that one doesn't have any motion at all. This is the error I get:

RangeError: Error #1125: The index 1 is out of range 1.


Solution

  • You're getting that error because you're splicing your array while in a for loop.

    instead of using 'l' as your parameter for the for loop, use bulletList.length directly as every iteration it will look at the CURRENT length which will reflect anything spliced out of it. You'll also need subtract your iterator when splicing as that shifts all future indexes down by one.

           for (i = 0; i < bulletList.length; i++) {
                b = bulletList[i];
                b.sprite.x +=  b.vx;
                b.sprite.y +=  b.vy;
    
                if (b.sprite.x > 1200 || b.sprite.x < -100 || b.sprite.y < -1000) {
                    deleteBullet(b);
                    bulletList.splice(i,1);
                    i--;
                }
    
            }