Animation

  1. Home
  2. Computing & Technology
  3. Animation

Creating Random Motion with Flash ActionScripts and Math.random

By Adrien-Luc Sanders, About.com

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.

8 of 8

Index: Creating Random Motion with Flash ActionScripts and Math.random

  1. Part 1
  2. Part 2
  3. Part 3
  4. Part 4
  5. Part 5
  6. Part 6
  7. Part 7
  8. Part 8

Explore Animation

More from About.com

Animation

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

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

All rights reserved.