Random Movement in AS3
- Page 1
by
kirupa | 24 December 2010
Have questions? Discuss this Flash / ActionScript
tutorial with others on the forums.
The thing that got me into Flash many many years ago is
learning how to make things move using code. One of the
first things I ever did was have circles move around the
screen...randomly. Random movement is fun because it isn't
boring. Unlike animations where things move in a pre-defined
fashion, the technique you will learn in this deconstruction
article will help you create animations that are more
life-like and unpredictable.
The following is the example whose code I will
deconstruct in this article:
[ click the green Refresh icon to see the
pre-loader in action again ]
While you won't be creating an application from scratch,
you will still learn some interesting details on how to make
things animate to a random destination using nothing but a
single movie clip and less than 100 lines of code.
First, go ahead and download the source for the Flash CS5
application:
Once you have downloaded the files, extract all of them
to a location on disk. You should see four files:
[ your extracted files ]
Launch Flash CS5 and go ahead and open
randomMovement.fla (or
randomMovementCS4.fla if you are using Flash CS4) and the two AS files
BlueCircle and Main. Once you have
done this, you have an exact copy of the application whose
output you saw happily moving around earlier.
Switch into your FLA file randomMovement and Press Ctrl +
Enter (Control | Test Movie | Test):
[ the circles are moving randomly! ]
You should see on your Flash player a replica of the
randomly moving blue circles you saw earlier.
Deconstructions are only fun if you understand end-to-end
how everything fits in. This article is divided into several
sections alternating between describing code and taking a
higher level look at what is being done. With that, let's
start with our first attempt at describing what is going on:
At the very beginning, the
application loads a blue circle that you had drawn and
converted into a MovieClip. This MovieClip has a class
associated with it, and that class is called
BlueCircle. What this means is that if you instantiate a
BlueCircle object in code and add that to your stage, a
lovely blue circle will greet you when you run your
application.
Getting the circles to display,
and getting them to move are two separate things each
handled in their own class file. Getting the circles to
display is handled by Main.as, and the Main class is the
document class for your Flash file.
Once a BlueCircle object
is added to your stage, everything from randomly positioning
itself initially to moving to a random destination are
specified entirely within the BlueCircle class.
In the next few pages, let's take the above summary and
dive much deeper into how exactly it was done.
Onwards to the
next page!
|