0

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.

tversteeg
  • 4,717
  • 10
  • 42
  • 77

1 Answers1

1

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

        }
BadFeelingAboutThis
  • 14,445
  • 2
  • 33
  • 40
  • Thank you very much! It are always the most of the simple things I can't come up with when I find such an error.. And the i-- is not necessary, this works just fine! – tversteeg Aug 15 '12 at 21:27
  • I updated my answer with another thought. everytime you splice your array you'd end up skipping the next object in the array if you don't do i-- – BadFeelingAboutThis Aug 15 '12 at 21:28
  • Oh yeah your right, I never figured that out but I also never had trouble with it. – tversteeg Aug 15 '12 at 21:32
  • You can also iterate backwards over the array, that way deleting the last element doesn't hurt :) – Sunil D. Aug 16 '12 at 04:14
  • Yes but iterating backwards costs more performance, and I also found a way to do it the way I wanted, which is also better for performance! I edited it in my question. – tversteeg Aug 16 '12 at 10:30