# 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.