Craig
Craig

Reputation: 51

Accessing Bitmaps created in a loop (AS3)

I have a function that I call which uses a loop to create some bitmaps of spikes. Here's the bitmap variable with global scope:

public var spikes:Bitmap;

//...

And here's the function with the loop:

private function generateSpikes():void
    {
        for (var i:int = 0; i < 5; i++)
        {
            spikes = new SpikesImage();
            spikes.x = (Math.random() * 500) - spikes.width;
            spikes.y = (i * yDistanceBetweenSpikes) + (player.height + 300);

            addChild(spikes);
        }

Later in my enterFrame function, I have the statement:

spikes.x += 10;

This only moves one of the spikes bitmaps though, and I'm wanting to move all of the spikes bitmaps created within the loop. How would I go about this?

Upvotes: 0

Views: 60

Answers (1)

Josh
Josh

Reputation: 8149

Basically, spikes is ONLY the final object set in the loop. So you need to make all of the other objects created available in another fashion. Generally, the way people do this is by storing them in an array.

private var spikeArray:Array = [];
public var spikes:Bitmap;

private function generateSpikes():void
{
    for (var i:int = 0; i < 5; i++)
    {
        spikes = new SpikesImage();
        spikes.x = (Math.random() * 500) - spikes.width;
        spikes.y = (i * yDistanceBetweenSpikes) + (player.height + 300);

        addChild(spikes);
        spikeArray.push(spikes);
    }
}

Then you can access them by looping through that array or calling a specific index of that array.

Upvotes: 1

Related Questions