3

I've been having a problem with my Actionscript code. I am fairly new to Flash and AS3, so I apologize if my code seems crude or rudimentary, but I'm doing this as best as I can.

Well, in this project I'm trying to get a bullet to ricochet off a wall once. If it hits a wall again after ricocheting, the bullet will disappear.

I've created a for loop which moves the bullets, in an array. At the same time, I try to keep track of each bullet's individual number of ricochets. This works fine when I shoot a first bullet - it will ricochet and then disappear after hitting another wall. However, every bullet I fire after that disappears on the first wall it hits, before it has ricocheted. I've tried to get this to work but I just can't seem to do it.

I would be grateful if somebody could show me the problem, or suggest a change to my code. Here is a link to my code as it is now.

Thanks, to anybody who helps.

dejjub-AIS
  • 1,501
  • 2
  • 24
  • 50
Lucas
  • 43
  • 5

2 Answers2

1

Here are some suggestions I have:

1: Create a Bullet class that tracks its own collisions against walls. I'd also move the clearBullet() method into the bullet class itself.

public class Bullet extends Sprite
{

    public var collisions:int = 0;
    public var xv:Number = 0;
    public var yv:Number = 0;


    public function clear():void
    {
        if(parent)
            parent.removeChild(this);
    }

}

2: Update your loop to deal with this new info.

for each(var i:Bullet in bulletholder)
{
    // Move bullet.
    // Check for collision.

    // When there is a collision, do this:
    i.collisions ++;

    if(i.collisions >= 2)
    {
        var n:int = bulletholder.indexOf(i);
        bulletholder.splice(n, 1);

        i.clear();
    }
    else
    {
        // Deal with changing bullet position.
    }
}
Marty
  • 39,033
  • 19
  • 93
  • 162
1

I see at least a couple of problems with your code:

  1. Your ricochetcount is clearly out of sync. i.e. you need to delete an element from that array as well.
  2. When you delete an element from the bulletholder array (via clearBullet), you're still incrementing i, which means you end up inadvertently skipping an element.

Also I'm not sure why you need clearBullet(). You already have the index i as well as a reference to the bullet object right there in the main loop.

Manish
  • 3,472
  • 1
  • 17
  • 16