My examples are all going to be on a stage that's 300x200, but you can work with a larger or smaller area if you wish.
You'll need to create a movieclip that will move randomly. I used a red circle.
The simplest way to make your movieclip move randomly is to add (or subtract) a random number to both the _x and _y properties of your MC. This is most easily done by like so:
onClipEvent(enterFrame){
//random(7)-3 gives a number from -3 to 3
_x+=random(7)-3;
_y+=random(7)-3;
}
Test your movie and your MC should start jittering around randomly. Now, this may be far too jumpy for your taste, so lets mae it move more smoothly.
In order to make the movement smoother, we're going to reduce how frequently the MC switches directions. In order to do that, we'll set a direction variables and increment the _x and _y properties with them. We'll then test a random number to see if we should change the direction variables.
onClipEvent(load){
xDir=random(3)-1;
yDir=random(3)-1;
}
onClipEvent(enterFrame){
_x+=xDir;
_y+=yDir;
//random(3)-1 gives a number from -1 to 1
if (random(10) == 0){
xDir=random(3)-1;
}
if (random(10) == 0){
yDir=random(3)-1;
}
}
When you run that, you'll notice that sometimes your MC will stop. This is because random(3)-1 returns -1, 0, or 1. When both xDir and yDir are 0, the MC pauses. If you want the MC to always be moving, you can change the code like so:
onClipEvent(load){
xDir=1;
yDir=1;
}
onClipEvent(enterFrame){
_x+=xDir;
_y+=yDir;
//random(3)-1 gives a number from -1 to 1
if (random(10) == 0){
xDir*=-1;
}
if (random(10) == 0){
yDir*=-1;
}
}
The above code will flip both xDir and yDir between 1 and -1 randomly.
Obviously, you can change any of the random number generators to make your MC move more quickly. If you want a number from -n to n, the code should be random(n*2+1)-n.
This is what each of the 3 different approaches I've outlined looks like:
Source .fla (Flash 8 format)
If you can't see the examples, try upgrading to the latest Flash Player and try the file again.
