Craig
Craig

Reputation: 51

Using a loop to create multiple childs of the same bitmap (AS3)

I have a bitmap that I want more than one of at different positions on the stage. I'd guess that this is achievable using a loop but I'm not sure how.

Currently I have:

[[Embed(source="../lib/Spikes.png")] //Spikes
    public var SpikesImage:Class;

public var spikesBitmap:Bitmap = new SpikesImage();

Upvotes: 0

Views: 159

Answers (1)

Marty
Marty

Reputation: 39458

Using a loop to create multiple instances of SpikesImage:

for(var i:int = 0; i < 10; i++)
{
    var spikes:Bitmap = new SpikesImage();
    spikes.x = i * spikes.width;

    addChild(spikes);
}

Though this would consume far more memory than if you were to have one Bitmap on the stage, and use copyPixels() to draw the data of SpikesImage onto that multiple times.

An example of that:

var screen:Bitmap = new Bitmap();
screen.bitmapData = new BitmapData(stage.stageWidth, stage.stageHeight);

var spikes:Bitmap = new SpikesImage();
var drawPosition:Point = new Point();
var drawRect:Rectangle = spikes.bitmapData.rect;

for(var i:int = 0; i < 10; i++)
{
    drawPosition.x = i * spikes.width;

    screen.bitmapData.copyPixels(
        spikes.bitmapData,
        drawRect,
        drawPosition
    );
}

addChild(screen);

The downfall of this approach however is that you lose the ability to transform the graphics in any way (rotate, scale).

Upvotes: 1

Related Questions