## Question of the Week

Random Motion
by kirupa

Oh no! Not another random motion tutorial on kirupa.com. There are already several, so why would I be writing another tutorial on random movement? The reason is that many of the excellent random motion tutorials on the site cater to a more actionscript-savvy audience.

My implementation accomplishes random motion by using simpler AS concepts that are, I hope, easily understandable by beginner Flashers. The following is an example of what this tutorial will help you to create:

[ the flowers - they are alive! ]

This tutorial will help you to create the above effect. You will also learn the 'behind-the-scenes' action of the code that makes the objects move randomly.

Here's How
The following steps are designed to work in Flash MX 2004, but they should work in Flash MX and maybe even Flash 5:

1. Create a new document in Flash. Set the movie's width to 300 and movie's height to 200. Set your Flash movie's frame rate to 25.
2. Now, draw a filled-in circle using the Circle tool. Your drawing area should look like the following image:

[ draw a circle ]

1. Once your circle has been drawn, select your circle and press F8. The Convert to Symbol dialog box should appear. Select the option for Movie Clip and press OK.
2. Select your newly converted movie clip if it is not selected. Give your movie clip the instance name, dot:

[ give your movie clip the instance name 'dot' ]

1. Now, select your movie clip and press F9. The actions dialog box will appear. Copy and paste the following section of code:
//data you may want to change
width = 300;
height = 200;
speed = Math.round(Math.random()*2)+1;
//initial positions
x = this._x=Math.random()*width;
y = this._y=Math.random()*height;
x_new = Math.random()*width;
y_new = Math.random()*height;
}
onClipEvent (enterFrame) {
//x movement
if (x_new>this._x) {
sign_x = 1;
} else {
sign_x = -1;
}
dx = Math.abs(x_new-this._x);
if ((dx>speed) || (dx<-speed)) {
this._x += sign_x*speed;
} else {
x_new = Math.random()*width;
}
//y movement
if (y_new>this._y) {
sign_y = 1;
} else {
sign_y = -1;
}
dy = Math.abs(y_new-this._y);
if ((dy>speed) || (dy<-speed)) {
this._y += sign_y*speed;
} else {
y_new = Math.random()*height;
}
}
1. Now, select the first frame of your timeline. Press F9 again to display the Actions dialog box for the frame. Copy and paste the following section of code into that frame:
i = 0;
while (i<25) {
//duplicateMovieClip(dot, "dot"+i, i);
dot.duplicateMovieClip("dot"+i, i);
i++;
}
1. Save this file. Give it any name you want. Go to File | Publish Preview | HTML. You should see something very similar to what you see in the example animation above. Of course, you will see randomly moving circles as opposed to randomly moving graphics.

Well, you have the easy part of the tutorial finished. The next page will explain why the code works.

 SHARE: