简体   繁体   中英

How to add movie clips to stage in a grid fashion?

I have 9 'polaroid' movieclips that I want to add in a 3x3 grid, in a random order each time the movie is played.

I have the names of the polaroids in an array like so:

var animals:Array = ["lion_polaroid", "rhino_polaroid"...];

How can I create a function to add them to the stage? I guess my main issue is a) random position in the grid each time it loads and b) how to alter the x and y variables so that if there's more than 3 in a row, start a new row? This is as far as I've got without a brain fart..

var mySprite:DisplayObjectContainer = new Sprite();
stage.addChild(mySprite);

function addPolaroids() {
for (var i = 0; i < animals.length; i++) {
var polaroid[i]:DisplayObject = new [i]();
polaroid.x = ?;
polaroid.y = ?;
mySprite.addChild(polaroid);
 }
}

I've only been doing AS for less than a month so I'm sorry if this is a silly question. :) Any help is greatly appreciated. Thank you!

Easy. Integer division by 3 will give you Y-index, modulo by 3 will give you X-index.

polaroid.x = (i%3) * 100;
polaroid.y = int(i/3) * 100;

You can take a couple different approaches to the randomization. You can either randomize a array of positions, an then loop through the array and it put the pictures out based on those random coords.

function randomize ( a : *, b : * ) : int {
    return ( Math.random() > .5 ) ? 1 : -1;
}

var grid = [{x:0,y:0},{x:10,y:0},{x:20,y:0},{x:0,y:10},{x:10,y:10},{x:20,y:10},{x:0,y:20},{x:10,y:20},{x:20,y:20}];

grid.sort( randomize ) );

for(var i = 0 ; i < grid.length ; i++){
  polaroid.x = grid[i].x;
  polaroid.y = grid[i].y;
}

You can also randomize your pictures and then loop over them in a similar way.

function randomize ( a : *, b : * ) : int {

    return ( Math.random() > .5 ) ? 1 : -1;
}

var pictures = [pic1,pic2,pic3,ect];

pictures.sort( randomize ) );

var rows = 3;
var cols = 3;
var currentRow = 0;
var currentCol = 0;
var rowHeight = 50;
var colWidth = 50;
for(var i = 0 ; i < rows*cols ; i++){
  polaroid.x = currentCol*colWidth;
  polaroid.y = currentRow*rowHeight;
  currentCol++;
  if(currentCol == 3){
     currentCol = 0;
     currentRow++;
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM