1. Home
  2. Computing & Technology
  3. Animation

Creating Random Motion with Flash ActionScripts and Math.random

By , About.com Guide

8 of 8

The way to keep your animation on the stage is to use if statements to limit its boundaries:

onClipEvent (enterFrame) {
if (this._x<500&&this._x.0) {
this._x=this_x + Math.random()*100;
}
if (this._x>=500) {
this._x=this_x - Math.random()*500;
}
if (this._y<400&&this._y.0) {
this._y=this_y + Math.random()*100;
}
if (this._y>=400) {
this._y=this_y - Math.random()*400;
}
}

That looks rather staggering and confusing, but it’s not. If you break it down line by line, it’s saying this:

If the horizontal position of my object is less than the width of my movie (in my case, 500 pixels) but greater than 0, then generate a random number, multiply it by 100, and advance the horizontal position of my object to the right by that amount. If, however, the horizontal position is greater than or equal to the width of my movie, then generate a random number, multiply it by the width of my movie, and then subtract that from my object’s current horizontal position to move it back by that many pixels.

It works similarly for the y (vertical) position. You can look here for my example.

Explore Animation
About.com Special Features

Holiday Central

What to eat, where to go, fun things to do and how to save money on the perfect gifts. More >

Family Tech Center

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

  1. Home
  2. Computing & Technology
  3. Animation
  4. Flash Animation Tutorials
  5. Creating Random Motion with Flash ActionScripts and Math.random

©2009 About.com, a part of The New York Times Company.

All rights reserved.