AS3 loop for positioning enemies

I am developing a game that functions like space invaders. so far I have the enemies spawning in a for loop like this:

for (var a=0; a<6; a++)
{ 
    var bd:MovieClip = new bdenemy();
    enemy1[a] = bd;
    addChild(enemy1[a]);
    enemy1[a].x = 50 + Math.random() * 700;
    enemy1[a].y = 50;
}

however when i run the game the enemies just spawn in those parameters, overlapping most of the time. how can i make it so that each new enemy is a set x distance from the previous one, using an array like this? Thanks.

Answers


Optimization

Before anything, you should declare your variable outside of the loop to avoid storing n variables.

Answer
Fill width

You may store the previous x in a variable and ensure there is a minimal gap between each enemy. This is if you want to fill your screen sidth with enemies, no matter how many of them.

var bd:MovieClip;
var previousX:uint=0;
while (previousX + 150 < stage.stageWidth)
{ 
    bd = new bdenemy();
    enemy1.push(bd);
    addChild(bd);
    bd.x = previousX + 50 + Math.random() * 100;
    bd.y = 50;
}

50 is the minimal gap between two enemies.

Fixed amount

If you want to have exactly 6 enemies, neatly dispatched on the screen you may introduce a position span for each.

var bd:MovieClip;
const N_ENEMIES:uint = 6;
var span:uint = stage.stageWidth / N_ENEMIES;
for (var i:int=0; i < N_ENEMIES; i++)
{ 
    bd = new bdenemy();
    enemy1[i] = bd;
    addChild(bd);
    bd.x = i * span + Math.random() * span;
    bd.y = 50;
}

There, each enemy will have a random position inside its span.


Need Your Help

Push notification different Messages for different servers ios

php ios json push-notification

I have set up many push notifications in iOS projects. I always receive the same message which I have sent from my application, all going well.

Documentation for Excel python COM object?

python excel com documentation

I want to use Python and COM to manipulate data and formula in Excel files. I've looked around a couple of modules in python but I have yet to find support for reading formulas. So I am forced to use