Saturday, July 12, 2014

Tip - For loops in Flash

When creating games in flash using actionscript, often times you want to move many objects at once, or test collision detection for many objects at once. While you could tell each Movie Clip to move with code similar to:

movieClip1.x = movieClip1.x + 5;
movieClip2.x = movieClip2.x + 5;
movieClip3.x = movieClip3.x + 5;
movieClip4.x = movieClip4.x + 5;
movieClip5.x = movieClip5.x + 5;

it would be a lot easier, neater, and easier to change in the future if you used a for loop. To start, create an array and add each movie clip that you want to move into the array. This can be done with the following code:

var movieClipsArray:Array = new Array(movieClip1,movieClip2,movieClip3,movieClip4,movieClip5);

Now, when you want to move all the movie clips you can simply type:

for(var i:Number = 0;i
    movieClipsArray[i].x = movieClipsArray[i].x + 5;
}

This code goes through each item in the array and tells it to move to the right. Now, if you wanted to change the distance each movie clip moved, you would only have to change one number, and if you wanted to add more movie clips that move, you would simply add the movie clip name to the list when you create the array.

Hope this helps you all out there,

James Grams

No comments: