-
Define
variables.
-
Generate
random numbers for the x and y positions.
-
Gradually
move the object to this position.
-
Tell
object to to repeat the process when it
reaches the new position.
accel = 4;
var randx = Math.round(Math.random()*Stage.width);
var randy = Math.round(Math.random()*Stage.height);
ball_mc.onEnterFrame = function (){
ball_mc._x += (randx-ball_mc._x)/accel;
ball_mc._y += (randy-ball_mc._y)/accel;
if(Math.round(ball_mc._x)==randx){
randx = Math.round(Math.random()*Stage.width);
randy = Math.round(Math.random()*Stage.height);
}
}
acceleration
= 10
jumpfactor
= 200
These
expressions in Actionscript define values.
This way when we need a value all we call
"acceleration". This is particularly
useful as i can change the value of acceleration
or jumpfactor at the top of my code and i only
have to edit one line of code instead of all
the places where the term acceleration appears,
saving loads of time!
newpos
= function () {
ranx = Math.round ((Math.random ()*jumpfactor));
rany = Math.round ((Math.random ()*jumpfactor));
}
Here
we have defined a new function that is responsible
for assigning a new position for the ball.
The "Math.random() is a built in function
in flash that creates a random number between
... and ... When multiplied by the jumpfactor
it magnifies the random number.
Since
we will need to logically evaluate this number
in the future we must round it so we put the
expression inside the Math.round function.
newpos();
This
calls the function "newpos()" asking
it to perform it's defined function at that
point in the time line.
this.onEnterFrame = function() {
this._x += ((ranx-this._x)/acceleration);
this._y += ((rany-this._y)/acceleration);
This
defines a new function. However the "this.onEnterFrame" code
instructs the function to operate every time
a new frame is entered on the main time line.
The
function takes the random number generated
from the first function subtracts the dimension
of the stage and divides it by the value acceleration.
inside
this function is its continuation condition:
if
(Math.round(this._x) == ranx || Math.round(this._y)
== rany) {
newpos();
}
This
code tells the green function to loop untill
it reaches its new location. It does this by
complementary logic.
stating
that only when the balls position is equal
to the defined "newpos() value can the "newpos()'
be called again.
}
this
curly bracket then closes the green function
|