Introduction
There is something about of randomness that appeals to people, kind of like watching fish in an aquarium.
Though the main reason that I am writing this tutorial is that other random motion tutorials that I have seen, use up unnecessarily large amounts of code for something as simple as random motion.
Flash Setup
Draw a circle (or whatever shape you want), select it and hit F8 to convert it to a movieclip, name this 'ball'.
Actionscript Breakdown
A break down of how the random motion script will work
- Generate a random value for the position
- Move the object gradually towards the random position value
- Once it reaches the position generate another random value, repeat the process
Note: All the actionscript used in the tutorial will be added on frame one of the movie clips timeline and not the main timeline (for simplicity's sake )
1. Generating the Random Position
First we need to generate a Random Position, we can generate a position pretty easily by using
newpos = function () {
ranx = Math.random ()*250)
rany = Math.random ()*250)
}
this.onEnterFrame = function() {
newpos ()
this._x = ranx;
this._y = rany;
}
In the function newpos () Math.Random () generates a random decimal number between 0 and 1, it is then multiplied by 250 which is the width of the movie. So in effect ranx and rany the random positions will be set to value
The this.onEnterFrame part calls the function newpos() continuously and sets the position of the movieclip to a random value
2. Gradually moving towards the random position
acceleration = 10
newpos = function () {
ranx = Math.round((Math.random ()*250));
rany = Math.round ((Math.random ()*250));
}
newpos();
this.onEnterFrame = function() {
this._x += ((ranx-this._x)/ acceleration);
this._y += ((rany-this._y)/ acceleration);
};
newpos() has been moved outside the onEnterFrame event because we want to move the movieclips gradually not every time the movieclip enters a frame.
this._y += ((rany-this._y)/ acceleration);is a shorthand way of saying
this._y = ((rany-this._y)/ acceleration) + this._y;
The code keeps adding a portion of the difference between the current movie clip position and the randomly generated position, on enterframe.
This way the the _x and _y values of the movieclip are gradually increased to match the the values of the randomly generated position.
3. Repeating the process
The process needs keep repeating so we add the following code.
acceleration = 10
newpos = function () {
ranx = Math.round((Math.random ()*250));
rany = Math.round ((Math.random ()*250));
}
newpos();
this.onEnterFrame = function() {
this._x += ((ranx-this._x)/acceleration);
this._y += ((rany-this._y)/acceleration);
if (Math.round(this._x) == ranx || Math.round(this._y) == rany) {
newpos();
}
};
This way once the _x value of the movieclip equals the random position. The newpos() function is called again to generate a new set of random x and y values and the whole process repeats itself over and over again.