For loops and attachMovie

Hi there,

I want to attach a MC dynamically so that I have 12 rows and 12 columns of _mc box on the main stage:


xpos = 50;
ypos = 50;
for(i=0;i<12;i++){
 
 this.attachMovie("box","bx"+i,i,{_x:xpos,_y:ypos});
 xpos+= this["bx"+i]._width+5;
 
}

The code attaches the MC in only one row. when I add:


ypos+= this["bx"+i]._height+5;

I get nothing on the stage.
I think it can be done only with a nested loop but so far, well, my head’s in a loop!

Any help much appreciated.
Geminian1

you can try my Grid class that no one seems to like but me… :slight_smile:

[AS] /**
Grid class
@author: Devon O.
@date: 15JAN06
/
//
//
class Grid extends Array
{
/
*
* Grid returns an array of x and y coordinates based on the number of columns, rows, height and width of cells,
* and the x and y value of the upper left corner.
*
* @usage myGrid=new Grid (columns, rows, cellHeight, cellWidth, topLeftCornerX, topLeftCornerY)
* @param cols: The number of columns
* @param rows: The number of rows
* @param cellHeight: The height of the grid cell
* @param cellWidth: The width of the grid cell
* @param x: The x position of the top left corner of the grid
* @param y: The y position of the top left corner of the grid
* @return Grid (an array of objects each containing two properties: x and y)
/
public function Grid (cols : Number, rows : Number, cellHeight : Number, cellWidth : Number, x : Number, y : Number)
{
var numCells : Number = cols * rows;
var curx : Number = x;
for (var i = 0; i < numCells; i ++)
{
this * = new Object (
{
x : curx, y : y
});
curx += cellWidth;
if ( ! ((i + 1) % cols))
{
curx = x;
y += cellHeight;
}
}
}
//
/
*
* The shuffle method will return the array of grid coordinates in a random order.
*
* @usage myGrid.shuffle()
* @return Void
*/
public function shuffle () : Void
{
var len : Number = this.length;
var temp : Object = new Object ();
for (var i = 0; i < len; i ++)
{
var rand : Number = Math.floor (Math.random () * len);
temp = this *;
this * = this [rand];
this [rand] = temp;
}
}
}[/AS]

To use:

[AS]// pretend the “box” mc is 25 pixels by 25 pixels and you want 5 pixels between them -
// that’s why the 30…
var myGrid:Grid = new Grid(12, 12, 30, 30, 50, 50);
var len:Number = myGrid.length;
for (var i = 0; i < len; i++) {
var myBox:MovieClip = this.attachMovie(“box”, “box” + i, i, {_x:myGrid*.x, _y:myGrid*.y});
}[/AS]

hope that helps out…

Hey Devonair,

Thanks for the help. It works beautifully but can it be done without having to write a class?

Geminian1

yeah, but the class is much nicer for modularity(word?)