This is an archived tutorial from the kirupa.com legacy collection. It covers software that may no longer be available, but it is kept online because the ideas still hold up.
Whew, it's been too long since I last wrote a tutorial so here we go...
Basically, we're going to make a MovieClip prototype that randomly moves an
object in all directions. What's special about this prototype is that it doesn't
override your onEnterFrame handler, so you can still do whatever you want as the
movieclip is randomly moving.
Here is an example of the random movement this tutorial will explain:
[ there you have it - random movement! ]
Moving on, I must first say that in order to understand this you must have at
least the basic knowledge of Actionscript, and foremost, how to add it (to
frames, movieclips, etc). With that aside, I present to you, the code:
[ copy and paste the above code into a frame ]
Copy and paste the above code into a frame of your animation. The code does not do much...for now! Also, don't let the length of the code fool you, it's actually shorter than it looks; I repeat a chunk of code, which I'll explain later on.
The first line to look at is:
MovieClip.prototype.moveRandom = function(max_dv, maxV, freq, behavior, fps)
If you have some sort of understanding for prototypes, good. If not, you'll know now. Prototypes are functions defined for a specific object which all copies or instances of the object can use. The object in question is MovieClip. We are defining a prototype function "moveRandom" for all MovieClips.
This means that any kind of MovieClip can call this function, but nothing else. Not Buttons, Sounds, Objects, Arrays, nothing, only MovieClips. Here we are merely defining the prototype, we aren't actually calling it. After "prototype" we have the function name, and afterwards, your general function declaration along with the parameters (max_dv, maxV, etc).
this.chgSpd = max_dv;
this.maxV = maxV;
this.freq = freq;
These three lines simply move the parameters you gave it into the object so it can be used later on.
this.vx = this.chgSpd*(Math.random()*2-1);
this.vy = this.chgSpd*(Math.random()*2-1);
Here we define the initial random speed.
If this looks confusing, let me explain:
Hopefully you will already know that the Math.random()
function returns a random value from 0 to (but excluding) 1.
In this little math line, we multiply that random value by 2
and subtract 1 from it. This gives us a random value from -1
to 1 (say our random value was 0.9999...times 2 gives us 2,
minus 1 equals 1; say our random number was 0, minus 1 is
-1, see?).
Now from this random range we multiply it by the chgSpd variable which is the maximum allowable change of speed. If chgSpd was 5, we'd get a value from -5 to 5. We assign a random value to both the horizontal and vertical speeds.
if (behavior == "bounce" || behavior != "mod") {
This little IF test sees the kind of behavior you want on the randomly moving objects once they encounter the wall. "bounce" will make it bounce off the wall and "mod" will make it appear on the other side of the screen when it goes off. This IF statement says "if behavior is 'bounce' continue to the following, OR if behavior is not 'mod', then continue as well". I have it like this because if the user doesn't give a behavior, then it will default to "mod" which I don't want it to do; so in simple terms "IF behavior is 'bounce' or anything else but 'mod', continue".
this.$mR = function() {
Here we define a function within the prototype. Don't let
the '$' fool you, it is just as valid a character for
functions as other letters. This just reminds me and you
that it's a private function and you don't want to use it
anywhere else but in here.
this._x += this.vx;
this._y += this.vy;
Here we simply move the object according to the velocity it
has on each direction. Nothing too complicated, I hope.
this.vx = (!(random(this.freq))) ? (this.vx+this.chgSpd*(Math.random()*2-1))%this.maxV : this.vx;
this.vy = (!(random(this.freq))) ? (this.vy+this.chgSpd*(Math.random()*2-1))%this.maxV : this.vy;
Here's where the real magic lies. Here is where we assign
the random velocities. I use the question mark, or tertiary
operator here. It is the same as an IF statement, only the
majority of the time it is used for assigning values based
on a condition. Here's a quick tutorial (within a tutorial)
on tertiary operators:
Value to be assigned = condition ? Assign this value if true
: Otherwise assign this value;
Notice the colon (:) there, separating the conditional
values. There are many other things you can do with tertiary
operators, but for this tutorial, I'm only going to show you
one of its uses.
Our condition for this conditional assignment is:
(!random(this.freq))
The random function, unlike it's younger (newer) brother, Math.random(), returns a value from 0 to whatever you give it as a parameter (here we have this.freq), but excluding that value. This condition will return true when a random calls a value that is 0. The NOT operator (!) makes this return true when it's 0 since 0 is false, NOTing it will make it true. This will return false for any other value. The higher the value of this.freq, the lower the chances of 0 popping up. This decides how often you want to change the speed of your object.
No, we aren't quite finished yet. There is more explaining to do, and you may also be interested in knowing how to implement this nifty piece of code. Onwards to the next section!
|
|
Continued...
Like I mentioned a few seconds ago, here is the second
page. Let's continue with the code explanation.
(this.vx+this.chgSpd*(Math.random()*2-1))%this.maxV
This is our TRUE condition value. If you recognize part of this from before, you'll see that we add some random value (from -this.chgSpd to this.chgSpd) to the current velocity. The "%this.maxV" keeps it within the maximum velocity limit.
If the velocity reaches above the limit, our modulus (%) brings it back down to zero. If you don't understand how modulus works, refer to the forums for help. There is a lot of kindly folk ready to explain it all to you.
This is our FALSE condition value. It simply reassigns the original value if it's not time to add some random value to our velocity.
if (this._x>Stage.width || this._x<0) {
this.vx = -this.vx;
}
if (this._y>Stage.height || this._y<0) {
this.vy = -this.vy;
}
This chunk of code simply changes the direction of the
object so it "bounces" off the wall. This is the code that's
given when you choose "bounce" or nothing (or something
else, not "mod") as a behavior.
if (this._x>Stage.width) {
this._x %= Stage.width;
}
if (this._x<0) {
this._x = Stage.width-this._x;
}
if (this._y>Stage.height) {
this._y %= Stage.height;
}
if (this._y<0) {
this._y = Stage.height-this._y;
}
This is the code to make the object appear on the other side of the screen when it goes off. This is called when you choose the "mod" as the behavior.
updateAfterEvent();
I'm not so sure if this line is really needed, but it updates the screen when change takes place, regardless of fps.
this.__INTERVAL = setInterval(this, "$mR", 1000/fps);
This is the code that enables
you to still hold on to your onEnterFrame. Basically
setInterval repeats some function ($mR) every (1000/fps)
milliseconds regardless of the main movie's fps setting.
Here I set it so that the animation plays at about the same
speed as the Movie's fps. If you want to play the animation
at 30 FPS, you set the fps parameter as 30. For 50 FPS, 50,
etc.
That pretty much covers the important parts of this
tutorial. Now for usage:
someMC.moveRandom(maximum absolute velocity change, maximum
velocity, frequency of velocity change, behavior - either
"bounce" or "mod" but don't put nothing or it won't work,
FPS you want it to play);
The following sections will explain how to implement this effect in your movie:
Dynamically Created Movie Clip - Dot Example
MovieClip.prototype.createDot = function(name, depth) {
var mc = createEmptyMovieClip(name, depth);
mc.lineStyle(15, 0, 100);
mc.lineTo(0.15, 0.45);
return mc;
};
for (i=0; i<10; ++i) {
mc = createDot("dot"+i, i);
mc._x = 275;
mc._y = 200;
mc.moveRandom(3, 5, 5, "mod", 30);
}Paste the above code below the code from the previous section in the same frame.
Manually Created Movie Clip
To apply this effect to a movie clip that you manually create, ensure that the object you are interested in moving is indeed a movie clip and add the following code to the movie clip:onClipEvent(load) { moveRandom(3, 5, 5, "mod", 30); }Note that you can adjust the parameters used in the function to adjust the random movement.
Duplicating an Existing Movie Clip
This is similar to the above example. Ensure that your movie clip has the above code added to it, but also ensure that your movie clip has an instance name. For our example, let's set the instance name of our movie clip to "thoriphes".
Your code to duplicate the movie clip, added to your frame's actions, would simply be:
do { duplicateMovieClip(thoriphes, "thoriphes"+k, k); k++; } while (k != 25);Where the 25 in the above code refers to the maximum number of movie clips that will be created. Search the site or forums for more information on how to use the duplicateMovieClip function.
I have provided the source file for the example animation found in the previous section (dynamically created dots), and I have also provided an example that uses the random movement code with the duplicated movie clip.
Well, that concludes this tutorial. I
hope you enjoy it as much as I enjoyed writing it. As
always, questions can be directed to the forum, my e-mail
address ([email protected]), or through AIM (boyhatesfrench).
| Manny
Dimatulac aka Thoriphes thoriphes.com |
Just a final word before we wrap up. What you've seen here is freshly baked content without added preservatives, artificial intelligence, ads, and algorithm-driven doodads. A huge thank you to all of you who buy kirupa's books, became a paid subscriber, watch the videos, and/or interact on the forums.
Your support keeps this site going! 😇
:: Copyright KIRUPA 2026 //--