Undo command works (the Undo feature is Overflow setting of Extend makes your gradi-
accessible by pressing Ctrl+Z). The default, ent fade off infinitely; a setting of Repeat lets
Document-level Undo, means that every time the gradient fade from the beginning to the
you undo (by pressing Ctrl+Z), you go back end and then repeat and fade from the begin-
to the state before the last change. Perhaps ning to the end; a setting of Reflect fades the
this is the most intuitive behavior. However, gradient from the beginning to the end, fades
the other option, Object-level Undo, is very it back up to the beginning, and continues to
useful. With this option, if you make changes fade it up and down. Another change to the
while inside one movie clip and then make way gradients work in Flash 8 is that radial
changes to another movie clip, you can gradients support a focal point, which means
return to the first clip and press Ctrl+Z to you can create oblong off-center radial
undo the last thing you did in that clip! It’s gradients.
the way Flash used to work (before version
Some of the new Flash 8 features appear
MX2004), and it’s back as a preference.
subtle or esoteric—and they are. Although the
The margins for your text fields are also 9-slice feature can be hard to see initially, it’s
easier to modify in Flash 8. You can now quite powerful. When you select the Enable
grab any one of the six handles, as shown in Guides for 9-slice Scaling option in a movie
Figure 1.6. In previous editions, there was clip’s Symbol Properties dialog box (shown in
only one special margin-changing handle; Figure 1.7), you are given four special guides
dragging any other handle scaled and that make a tic-tac-toe pattern on the clip’s
stretched the text rather than the text field. In contents. (The guides are editable only while
Flash 8, if you want to scale the text, you can you’re editing the symbol from the Library—
use the Free Transform tool or the Properties that is, not by double-clicking an instance on
panel’s W (width) and H (height) fields. the stage.)
The contents of your clip in the four outer
FIGURE 1.6 Drag any handle on a text field to modify the squares don’t get scaled when the clip is
margin width in Flash 8. scaled. The midsections stretch as needed but
not the corners. This means you can use a
single symbol scaled to multiple sizes and
dimensions, but the corners won’t stretch or
appear distorted. You can see the difference
In addition to the previously mentioned fact between shapes scaled in various ways with
that gradients can be applied to strokes, 9-slice scaling in Figure 1.8. Notice how the
gradients also sport a new overflow setting word close doesn’t appear stretched even
(accessible in the Color Mixer panel). An though the clip’s width and height vary.
14 CHAPTER 1: Exploring Flash 8
FIGURE 1.7 The Enable
Guides for 9-slice Scaling
option lets you identify
which portions of your clip
shouldn’t scale (the four
corner squares).
FIGURE 1.8 The same symbol scaled to different dimen- Flash Player
sions, yet the corners don’t scale.
Interestingly, it took a separate team about
the same size as the team that built Flash 8
Professional just to build the new Flash
player! Flash (the authoring tool) just creates
.swf files, but the Flash player has to render
those .swf files—plus work with all kinds of
browsers on different operating systems. And
it does all this with a file size under 1MB. My
point is that the Flash player makes many of
the new features possible. For example, Flash
player 8 now lets you load .png or .gif files.
You don’t even need to author your applica-
tion in Flash 8 to take advantage of this
NOTE feature, but your users will need the Flash
One drawback of the Enable Guides for 9-slice Scaling player 8 to properly load the content of your
option is that it doesn’t work when your clip contains files.
nested clips. Everything inside the movie clip on which
you want 9-slice scaling to work must be plain shapes This also means that, if you want to employ
(not clip instances). one of the new Flash 8 features, your users
must have the Flash player 8 plug-in
What’s New in Flash 8 15
installed. One nice new feature when plan- Two ways to face the prospect of forcing a
ning to deliver to an earlier version of the plug-in upgrade on your users are to look at
Flash Player is that you’re given feedback (as which new features you want (or need) and
to which features are not available) while to look at the upgrade experience the users
authoring. Say you select File, Publish will have to endure. Every Flash version has
Settings; click the Flash tab; and pick an older some killer feature that—for the right
target Flash player version (such as Flash project—makes an upgrade requirement
player 7). In that case, any newer Flash 8 worthwhile. I’d imagine the video quality or
features that don’t work in the older Flash alpha channels will be enough to convince
player version you selected are grayed out. many users to make the leap to Flash player
In fact, if, after you select an older Flash 8. Only you can answer whether a new
player, you attempt to access a grayed-out, feature is profound enough or saves you
off-limits feature such as 9-slice, you are enough time in production to require Flash
presented with a dialog box and the option to 8—but there’s a lot of new stuff that could
revisit your Publish Settings (as shown in easily tip the scale.
Figure 1.9).
The upgrade process to Flash player 8 has
been vastly improved through what’s called
FIGURE 1.9 Flash informs you when a feature is off-limits Express Install. If your user has Flash player
to the Flash player you’re targeting.
6.0r65 or later, he already has an integrated
feature you can trigger to install Flash player
8 inline. That is, the user doesn’t have to
download something, quit the browser, run
an installer, and so on. He simply clicks Yes
in a security dialog box that appears right
inside the Flash application (shown in Figure
1.10); a new browser window opens with
Although you, the developer, undoubtedly your content, and Flash player 8 has been
want to require your users to upgrade to Flash installed!
player 8 so you can use all the cool new
features, your boss, client, or customers might
FIGURE 1.10 The inline Express Install dialog box
not be so eager to upgrade their browser plug- appears inside your Flash application.
ins to Flash player 8. On one hand, I under-
stand this reality. It’s going to be a matter of
time before Flash player 8 is an accepted
minimum requirement for websites. However,
it’s also important that you educate your boss,
client, or customers.
Express Install is not the only upgrade
approach and has its drawbacks, such as
needing to first check which version the user
16 CHAPTER 1: Exploring Flash 8
has and creating a Flash player 6 .swf to Flash interface to control filters or blends,
perform the Express Install. Just read the 25- producing videos that use the new On2 VP6
page document and associated sample files codec, and using advanced FlashType text
in the Flash Deployment Kit (www. settings—none of which are fully supported
macromedia.com/go/fp_detectionkit), and in Flash Basic.
you’ll learn all the available options. I
Granted, Flash Basic is almost half the price
predict that this Express Install feature, along
of Flash Professional. But it’s not even that
with the killer features such as filters and
easy to purchase it. You can’t purchase Basic
video, will greatly accelerate the adoption
as part of Macromedia Studio 8 (the bundle
rate for Flash 8 (historically taking 12
that also includes Dreamweaver, Fireworks,
months for a new player version to reach
and Contribute). And all upgrades from any
80% of all Internet users).
older version of Flash lead to Flash
Professional. Ultimately, the only good
NOTE feature in Flash Basic is the fact there’s an
integrated upgrade system to turn your
The express install is simply the most advanced option
version of Basic into Flash Professional 8.
available because it performs the install from within
the older Flash player.Traditional ways of upgrading
users still exist. For example, the default .html gener-
ated when you publish automatically presents the user ActionScript Additions
with a traditional Active X install dialog box in Internet
Explorer or the Missing Plug-ins button in Netscape ActionScript hasn’t gotten the same facelift it
and Firefox. did when AS2.0 was introduced in Flash
MX2004. Nevertheless, there are some pretty
major additions to the ActionScript feature
Flash Professional 8 and Flash Basic 8 list—too many, in fact, to list them all here.
However, I’ll list the major new features in
I suppose this is a bit of a sour way to end an the following sections because most appear
otherwise exciting section about what’s possi- in later chapters (even if the appearance is
ble with Flash 8, but I have to explain the often hidden away in the support files).
differences between the two versions of the
Flash 8 product. Unlike the confusing and
subtle differences between Flash MX 2004 and A Programming Primer
Flash MX 2004 Professional, the split between Because the section that follows this section
Flash Professional 8 and Flash Basic 8 is covers new ActionScript features, you’ll find it
profound. In a nutshell, the only reason to peppered with terms such as variables,
purchase Flash Basic is if you need supple- instances, and properties. If this kind of infor-
mental copies for machines dedicated for mation is familiar to you, feel free to skip
some sort of Flash assembly line. Macromedia ahead to the next section (on the
says Basic is for the “occasional user,” which flash.filters package). If such terms are
is accurate if you don’t plan on using most of new to you, you’ll find additional definitions
the new Flash 8 features, including using the for such terms in the Glossary (as well as in
ActionScript Additions 17
Chapter 2). However, instead of having you underscore in their names). Movie clip
keep one thumb in the Glossary while you instances are the easiest type of object to
read this chapter, here’s a narrative defini- understand because you can see them. But
tion of the terms that appear throughout the there are also instances of the Sound and
rest of this chapter and the book. Let me Date classes—just to name two.
stress two things before I start: First, if you
find this material basic, don’t worry, I
promise you’ll get plenty of opportunities to NOTE
adapt the projects in this book and flex your I capitalized Sound and Date because, when you
programming skills. (I won’t treat anyone create an instance of these object types, you must use
like a baby.) If, on the other hand, this mate- the exact, case-sensitive spelling.
rial is totally new to you, this explanation
will only provide an introduction to the
Think of this analogy: People have properties
terms I use in this book. I don’t suspect this
(such as hair color, weight, and age) and cars
quick lesson will turn you into a hardcore
have properties (such as horsepower, make,
programmer, but at least you can follow
and model). Interestingly, sometimes two
along when I explain the code behind the
different object types share the same property.
scenes of each project. You don’t have to add
Cars and humans both have a weight prop-
any custom programming to build the proj-
erty. Similarly, movie clip instances and
ects, but you can. And for me to explain
button instances both have a width property.
what’s going on, I have to use a program-
Often, however, the available properties
mer’s vocabulary.
depend on the type of object you’re working
It’s easiest to start with the most common with. Sound instances have a duration prop-
object type, movie clips, because they have a erty, but movie clip instances don’t.
visual representation on stage. A movie clip
The good news is that the code you write to
symbol on stage is called an instance. You
address clips and their properties uses the
can give each instance on stage a unique
same form (or syntax) in every case regardless
instance name by using the Properties panel.
of the object type. Namely, the syntax to refer
The instance name is used in your
to an instance’s property always looks like
ActionScript code to refer to the clip—or,
this: myInstance.myProperty (or “object dot
more technically, to address the clip. The
property”). I use the prefix my to indicate
reason you don’t use the symbol name (from
something I made up so you don’t think the
the master Movie Clip symbol in the Library)
terms myInstance or myProperty are built in
is because you might have multiple instances
to ActionScript. Note that sometimes you
of that same symbol on stage and you want
want to set a property (perhaps set a clip
to address each one individually. Why would
instance’s _rotation property to make it
you want to address a clip? Usually to
spin); other times you’ll just need to get a
change one of its properties such as its posi-
property’s value to use within a larger
tion on stage (either its _x property or _y
statement. (A statement is a complete
property, although there are many other
properties and they don’t always have an
18 CHAPTER 1: Exploring Flash 8
instruction—basically one line of code.) or presses a key. Naturally, there are all kinds
Check out this example: of events, and like properties and methods,
myClip._x = otherClip._x
events vary depending on the object type. For
example, Sound instances trigger or fire
events when the event onSoundComplete is
When Flash encounters this line of code, it encountered (that is, when the sound ends).
interprets the code and executes the instruc- A button instance has an onPress event (but
tions (meaning it does what the code says to no onSoundComplete event). Just as trees can
do). In this example, the instance called fall in the woods without anyone to hear
myClip gets its _x property set to a value them, events can fire in Flash and—unless
equal to the _x property of another instance your code is listening for that event—they go
called otherClip. (Anytime you see a single unnoticed. You have to write code to trap (or
equals sign, it’s an assignment meaning “is listen for) an event and define exactly how
now equal to,” as in “myClip’s _x is now you want to handle that event. What’s a little
equal to otherClip’s _x”.) Notice that you’re freaky is that events are really properties to
setting the _x property of myClip but only which you assign a value. Just as you might
getting the property of otherClip. say myClip._x = 100 (to make the clip
appear at the x position of 100), you
Another important concept is methods.
could say myClip.onEnterFrame =
Methods are like processes or procedures
myAnimationFunction—that says the myClip’s
applied to a single instance. You can also
onEnterFrame event (which fires every 1/12 of
think of methods as the capabilities a partic-
a second if your frame rate is 12 fps)
ular object type supports. Back to the human
is now equal to something called
analogy: walk, talk, and comb your hair are
myAnimationFunction. In both cases, a prop-
all methods—they’re all things an instance of
erty (_x or onEnterFrame) is assigned a value.
a human being is capable of doing. Methods
In this case, the value of the _x property is
you can apply to movie clip instances
assigned a value in the data type Number. If
include play(), stop(), and gotoAndPlay(). I
you were to assign the label property for a
like to compare properties to methods
Button component, you would want to use a
because their syntaxes are nearly identical.
value of the data type String. The value you
It’s always “object dot method,” as in
assign to an event is of the type Function.
myClip.play(). An easy way to distinguish
methods is that they always have parenthe- You can create variables as a way to store
ses. Some methods accept parameters (also data for later use. For example, you could
called arguments) that provide needed addi- assign a variable’s value with this code:
tional details. For example, when you say myName = “Phillip” (which means the vari-
myClip.gotoAndPlay(1), 1 is a parameter able named myName is now equal to the string
indicating which frame you want to go to. “Phillip”). You can change the value of a
variable by simply reassigning a value, but
Events are things that happen while a Flash
at any one instant, a variable has a single
movie plays. The most intuitive event types
value. You can store any data type in your
are things the user does, such as clicks, drags,
variable, but you’ll often want to type your
ActionScript Additions 19
variables—that is, to define the variable with Sometimes the class you instantiate is part of
the data type it is allowed to contain. Here is Flash and other times the definition for its
an example of typing the myName variable as behavior resides in a class file (MyClass.as,
a String data type: for example). For instance, I created an
EventChannel class (in a file named
var myName:String = “Phillip”;
EventChannel.as) for Chapter 3. You create
an instance by using the following syntax:
The reason you type a variable is simply so
myECInstance = new EventChannel();
that Flash will give you a warning when you
publish if you write code that tries to assign a
value that doesn’t match the data type you After you have an instance of a class stored
declared. That way, Flash helps you uncover in a variable, you can do anything you want
mistakes in your code. with that instance. That is, the class will
probably expose public methods, which are
methods you’re allowed to access and trigger.
NOTE Just as you can say myMovieClip.play(),
In future versions of the Flash player, typing your vari- you can also say myECInstance.
ables will make your projects perform much faster. startMonitoring() because I defined a
public method called startMonitoring().
(Exactly what happens when that method
Finally, terms such as object and class are
gets triggered depends on what the program-
thrown around a lot, but they’re actually
mer designed the class to do.) I should note
quite simple. I’ve been talking about movie
that private methods can be triggered only
clip instances because they’re so common,
from within the class itself; they are like
but they’re actually instances of the class
internal utilities to help the class do its work.
MovieClip. You could say that their object
type is MovieClip. Instances of the class Many times, you need to reference a class’s
MovieClip are easy to understand because complete path, as in this example:
you make an instance by simply dragging the myInstance = new
symbol from the Library onto the stage. For foldername.subfolder.MyClass()
most other object types, you must formally
instantiate them (as in “make an instance
I’ll discuss class paths in Chapter 2, but just
of”). You always instantiate an instance of a
realize that there may be a MyClass class in
class by using this syntax:
the previous path shown and another—
myInstance = new MyClass() completely different—version of the same
name in another path. There’s no conflict
You replace MyClass with the class you’re because the code doesn’t refer to MyClass but
instantiating. (By convention, all class names rather to foldername.subfolder.MyClass.
begin with an uppercase character.) Think how we have a president (like the
20 CHAPTER 1: Exploring Flash 8
president of the United States), but you can code applies a BlurFilter with a factor of 50
also have the Portland Cactus Collectors to a clip instance named myClip when the
President—and they reference different posi- user clicks the stage; it then applies a differ-
tions. A class path is like a qualifier. ent filter, with a factor of 5, when the user
lets go:
With your ActionScript primer out of the way,
we will move onto the key new ActionScript onMouseDown = function(){
features in Flash 8. var veryBlurry =
new flash.filters.BlurFilter(50,50);
myClip.filters = [ veryBlurry ];
The flash.filters Package }
onMouseUp = function(){
Filters can be applied using the Filters panel var lessBlurry =
(while authoring) or using ActionScript code. new flash.filters.BlurFilter(5,5);
This enables you to write scripts that modify a myClip.filters = [ lessBlurry ];
filter’s effect at runtime. For example, you }
could make some text get blurrier as the user
moves the mouse away and sharper as the The flash.filters package lets you create
mouse moves closer. Writing the code to any kind of filter the Filters panel can create,
apply a filter at runtime is a two-step process. but you do it with ActionScript so it can
First, you create a filter instance and store it respond to any event, such as the user’s
in a variable. Second, you apply the filter to a mouse movement. One other thing to note is
movie clip instance through its filters prop- that movie clip instances in Flash 8 have a
erty. If you want to change the filter applied filters property.
to a clip, you simply modify the filter or
create another filter with different properties In addition to ActionScript equivalents to all
and (in either case) overwrite the clip’s the filters in the Filters panel, ActionScript
filters property. Here’s a simple example in offers three other classes (in the
which we apply a blur filter to a movie clip flash.filters package) for even more
instance named myClip: advanced effects—namely,
ColorMatrixFilter, DisplacementMapFilter,
myFilter = new flash.filters.BlurFilter(); and ConvolutionFilter. You’ll learn more
myClip.filters = [ myFilter ]; about these in Chapter 9, “Creating Special
Effects.” They’re identical to the
Notice that the filters property is assigned an flash.filters package in that you still
array that contains just one item (myFilter). apply them to the filters property, but the
By putting more filters in the array you can way in which you create them is much more
apply more than one filter. In addition, you involved.
can set various parameters when you first call
the BlurFilter() function to affect how
much of a blur you want. For example, this
ActionScript Additions 21
myClip.attachBitmap(myBitmap, 0);
Package Names
Many of the names used in the section headings that For some reason, I often forget that second
follow are based on the respective class package name.
parameter (the level number), but this
A package is simply the folder path to where the class
parameter works the same way as how
files are defined (within the Classes\FP8 folder
attachMovie() places a clip into a level
inside the FirstRun folder adjacent to your installed
version of Flash).The reason you’ll want to become number. Every object, BitmapData or
familiar with these paths is that you need to include MovieClip, that you create dynamically is
the full package path in your ActionScript code. For placed into its own level within another
example, to use the BitmapData class, you have to say movie clip—even if that movie clip is the
flash.display.BitmapData. Chapter 2,“Producing main Timeline. The higher level numbers
a Flash Project,” covers more of the technical details of make the object appear above objects in
referring to ActionScript classes (including how to use lower-numbered levels. For the preceding
the import statement), but for now, realize that I code to work, you’d have to have previously
included the package names in the following descrip- created the myBitmap instance. Chapter 2
tions to be more explicit and help begin to make them
shows a simple example using the
more familiar.
BitmapData class.
I use the BitmapData class constantly to effec-
The flash.display.BitmapData Class tively take a snapshot of part of the screen.
For example, if I need to fade out one image
There’s just one class in the flash.display while another image fades in, I simply make
package, and it’s a powerful one. Many a BitmapData instance by copying the pixels
people believe the BitmapData class is the from the outgoing image. Then I attach that
biggest improvement in Flash 8. Basically, it’s BitmapData copy to a new clip (that I place
a way to store raster images, which are really on top of the old clip) and then load a new
just grids of pixels, into variables. You can image into the old clip. When the new image
create a bitmap image from scratch (for is fully loaded, I can fade out the clip with
example, you can create a grid of 10 × 10 the BitmapData instance. This is the same
white pixels); you can load a bitmap from an technique used in Chapter 4, “Creating a
image in your library (effectively copying the Portfolio.”
pixels from an imported image); or you can
copy pixels from an area or a clip on stage.
After the bitmap data is stored in a variable,
The flash.geom Package
you can modify it—for example, you can On the surface, you might think the classes
change its contrast or shape—and then in the flash.geom package would be attrac-
display it on stage. This key step (necessary tive only to a true geometry nerd. And, in
to see a BitmapData instance) is the fact, when you look at flash.geom.Point
MovieClip class’ attachBitmap() method. and flash.geom.Rectangle, they’re pretty
This method works just like attachMovie(), much as you might expect: They offer
as you can see in the following example: methods for such things as calculating the
22 CHAPTER 1: Exploring Flash 8
distance between two points or determining scrolling) a camera’s view of an object. For
the union between two rectangles. First, example, this code makes it appear as
doing those sorts of operations in the past though the myClip instance’s contents are
was much harder—so this package actually shifting to the left when in fact it’s just the
makes things easier. In the past, for example, scrollRect that is moving to the right:
calculating the distance between two clips var panX:Number = 0;
(say, instances mc1 and mc2) required you to onEnterFrame = function (){
remember the Pythagorean Theorem (you panX++;
know, a squared plus b squared equals c myClip.scrollRect =
squared—except to solve for c you need to new flash.geom.Rectangle(panX,
0,
take the square root) and this not-so-lucid
200,
code: 200);
a = mc1._x - mc2._x; }
b = mc1._y - mc2._y;
cSquared = (a * a) + (b * b);
c = Math.sqrt( cSquared ); Another movie clip property related to the
trace(“distance is “ + c); flash.geom package is transform. This prop-
erty actually contains several other proper-
ties, but I’ll start with just transform.matrix.
Using the new flash.geom.Point class makes
The transform.matrix property is a way to
it much clearer, I believe:
store all of a clip’s properties (such as _x, _y,
a = new flash.geom.Point(mc1._x, mc1._y); and _xscale) in a single array (really, a
b = new flash.geom.Point(mc2._x, mc2._y); matrix of six numbers). In fact, you never
c = flash.geom.Point.distance(a, b);
have to use _x or _y again if you don’t
trace(“distance is “ + c);
want—all you have to do is modify the
clip’s transform.matrix property. The
In addition to helping you solve geometry transform.matrix can get very complicated.
problems, you’ll also end up using the classes
I have a simple and practical example in
in the flash.geom package because several
case you think matrixes are necessarily more
other classes require that you pass parame-
complex than properties such as _x and _y.
ters with the data type Point or Rectangle.
Suppose you want to set all the properties of
In fact, every project in this book uses this
one clip (instance name oneClip) to match
package!
another clip (with an instance name
Like the new filters property for movie clip otherClip). The “old” way would look like
instances, movie clips have new properties this:
related to the flash.geom package. For oneClip._x = otherClip._x;
example, there’s a new scrollRect property oneClip._y = otherClip._y;
you can set equal to a Rectangle instance. oneClip._xscale = otherClip._xscale;
This is like a mask because it reveals a oneClip._yscale = otherClip._yscale;
//and so on ad infinitum
rectangular portion of the clip, but the
scrollRect property is more like panning (or
ActionScript Additions 23
The first line of code says, “the _x of the programming, you’ll find that they will dras-
oneClip instance is now equal to the _x prop- tically simplify your ActionScript code.
erty of the otherClip instance.” Then it
continues for every property. Not only is that
The flash.external.ExternalInterface
wordy, but there’s no property for skew or
tint.
Class
This class provides an easy way for Flash to
Check out the “new” way that uses only one
trigger JavaScript code (contained in the
line:
HTML web page that is hosting your .swf
oneClip.transform.matrix = file) or for JavaScript code to trigger
otherClip.transform.matrix;
ActionScript code in your .swf file. Although
you could send messages between JavaScript
Because the transform.matrix property only and ActionScript in the past, doing so wasn’t
reflects a clip’s scaling, rotation, and position very consistent and always required that the
(called the translation on a clip), you must values being passed back and forth be of the
use the transform.colorTransform property String data type. Now you can pass any
to grab any tinting applied to the otherClip data type, such as an Array or a Number. In
instance. You could add this line to copy the addition, calls are synchronous now,
tint as well: meaning you can call a remote method and
get an immediate response.
oneClip.transform.colorTransform =
otherClip2.transform.colorTransform; Going from Flash ActionScript code to
JavaScript code is really simple: Just use the
call() method and pass the function name
Like I said, classes from the flash.geom
you want to trigger as a string followed by
package (and, perhaps more to the point,
any parameters, which, incidentally, don’t
movie clip properties such as scrollRect and
have to be strings. Listing 1.1 shows the basic
transform) appear in most of the projects in
form of the call() method, and Listing 1.2
this book. After you grasp the core concepts
shows specifically how to trigger JavaScript’s
of using these classes in your ActionScript
built-in alert() method.
LISTING 1.1 Triggering flash.external.ExternalInterface.call(“methodName”,”parameter”);
JavaScript from Inside Flash
LISTING 1.2 Triggering flash.external.ExternalInterface.call(“alert”, “hello”);
JavaScript’s alert() Method
from Inside Flash
24 CHAPTER 1: Exploring Flash 8
In Chapter 6, “Saving and Evaluating Quiz Explorer gets a reference to the Flash object
Results,” you’ll see the ExternalInterface class (line 13) is different from how it is for
used as a way for a .swf file to ask JavaScript Netscape or Firefox (line 16). This code
to parse a query string in the HTML. assumes just two items not shown. First, the
object and embed tags for your Flash movie
Going from JavaScript to Flash ActionScript
need to contain id=”example” and
isn’t much more difficult, but because we
name=”example”, respectively, because that’s
don’t do it in any projects in this book, it’s
the object name being referenced in line 8.
worth detailing here. Letting JavaScript talk to
(Those tags are added automatically if you
Flash involves two steps: Make the call from
publish a file called example.swf.) In addi-
inside JavaScript and, from inside your Flash
tion, somewhere in the HTML file, you need to
file, identify the methods you want to expose
trigger the doit() function. For example:
to JavaScript. Here’s how: In the HTML file,
you must include the code in Listing 1.3.
homemade function called
exposedFunction() and passes an array
called myArray. The thisMovie() method gets
The Flash ActionScript side of this example is
a reference to the Flash object. You can see in
shown in Listing 1.4.
lines 12–17 that the exact way Internet
LISTING 1.3 JavaScript 1
Triggering a Function Inside 2 function doit() {
Flash 3 var myArray = new Array();
4 myArray.push(“this”);
5 myArray.push(“that”);
6 myArray.push(“the other”);
7
8 thisMovie(“example”).exposedFunction(myArray);
9 }
10
11 function thisMovie(movieName) {
12 if (navigator.appName.indexOf(“Microsoft”) != -1) {
13 return window[movieName]
14 }
15 else {
16 return document[movieName]
17 }
18 }
19
ActionScript Additions 25
LISTING 1.4 How Flash function exposedFunction(data:Array){
Exposes a Function for var total = data.length;
JavaScript to Trigger results_txt.text = “got an array with “ +total + “ items”;
}
var methodName:String = “exposedFunction”;
var methodReference:Function = exposedFunction;
flash.external.ExternalInterface.addCallback(methodName,
null,
methodReference);
The exposedFunction() method is plain old (that is, your code) from seeing the file’s full
Flash code. The last three lines of code are the path. A user won’t want to reveal her
steps you need to take to grant access to computer’s folder structure to your application
exposedFunction(). That is, JavaScript can’t because that information could get sent back
just reach in and trigger Flash code without up to your server. Because of this security
the formal step of using the addCallback() feature, you can’t ask the user to select a file,
method. such as an .mp3, and then immediately play
that music file for her. (You could upload it
The ExternalInterface class is a huge step
and then play it, but that’s totally different
forward for any project that needs to pass
and a very slow prospect considering how
data back and forth to a hosted environment.
large files can be.)
This time I said hosted environment instead of
JavaScript to draw attention to the fact that When the user points to a file, she’s granting
ExternalInterface is not limited to working you access to copy that onto your server.
only with JavaScript. As you’ll see in Chapter
There’s also a download() method that shows
8, “Creating a CD-ROM Front End,” there are
the user a save as dialog box to allow her to
third-party projector-making tools, and these
download files from your server to her hard
can benefit from the ExternalInterface class.
drive.
Integrating this sort of file upload/download
The flash.net Package functionality into a Flash project in the past
The flash.net package lets you present a required complex and, ultimately, clunky use
standard file open dialog box that viewers of multiple HTML windows. Now you can do
can use to browse to and select a file they it all from inside a Flash application. In fact,
want to upload. Then your code can upload you will do exactly that in Chapter 10,
that file. This process is secure for the user “Building a Photo Share Application,” where
because the Flash player prevents the .swf file you make a photo-sharing application.
26 ActionScript Additions
TIP
Here’s a tiny addition that’s not documented and
doesn’t really fit into any of the chapters in this
book—but it’s quite useful and officially supported.
The setTimeout() and clearTimeout() methods
are just like the existing setInterval() and
clearInterval() methods, but setTimeout() fires
only once. setInterval() lets you trigger the same
code repeatedly on a specified time interval—say,
every 2 seconds.You can use it to animate something
across the screen. Although that’s great for something
that continues indefinitely, it’s a bit of a chore to keep
track of all your intervals and clear them using
clearInterval()—but that’s just the way it works.
For the situations when you want something to
happen, but not right away, and you want it to happen
only once, you can use the new setTimeout() func-
tion. For example, if you want a display that reads
time’s up to appear after 10 seconds, you can use
this code:
clip._visible = false;
setTimeout(function(){
clip._visible = true;
}, 10000);
The last parameter is in milliseconds.
Final Thoughts
I’m sorry if this chapter sounded like a sales
job, but I actually restrained myself. The rest
of the book is more matter of fact. The
project-based chapters are all focused on
specific tasks. Throughout the project chap-
ters, I point out potential pitfalls and an
occasional opinion based on my experiences.
But in this chapter, my purpose was to get
you psyched for the sorts of stuff you can do
with Flash 8.
Final Thoughts 27
This page intentionally left blank
CHAPTER 2:
Project
Producing a Flash @ work
There are three general things you do in Flash: create graphics, animate in the
timeline, and add programming (which, in addition to making your project behave
differently based on data or user input, can in turn produce graphics and anima-
tions). This chapter focuses on the programming. However, I want you to see how
the graphics, animations, and programming elements are all connected. The most
important question answered in this chapter is, “Where do I put stuff to make it
behave the way I want?”
I hope that most of the basic Flash information covered in this chapter is familiar to
you. But, even if it seems too straightforward, please read it anyway because I make
many statements about what I believe are best practices. My recommendations
should help you avoid frustration. It’s alright if you don’t agree with my prefer-
ences, but at least hear where I’m coming from. Everything is based on my experi-
ence teaching Flash to many students over the years. Besides, the content here is
very concise.
In the last section of this chapter, you’ll get a good sense of exactly how you’ll be
creating the projects that follow in the remaining chapters. Although each project
chapter is different, they all draw from a few general frameworks. I’m sure that
after you build a few projects, you’ll begin to see similarities; this chapter introduces
everything more formally.
You can download the source and starter files from the accompanying CD-ROM.
Flash’s File Structure
Flash is unlike many document-creation tools in that you don’t have a “document”
(what the user sees) and the “tools” required to create or modify the document. It’s
fair to say Flash’s stage is the document and the various panels (all accessible from
the Windows menu) are the creation tools. But there’s so much more when you
consider such facts as these: The timeline can have multiple frames; movie clips
have their own timelines and can contain nested movie clips; and the scripts you
write can cause the movie to jump around the different frames in a timeline in a
nonlinear fashion, as well as change the appearance of any movie clip. Let’s discuss
some of the big concepts and the pitfalls to The timeline shown in Figure 2.2 has dots in
avoid. every frame, meaning each frame is a
keyframe. That would be the case if you drew
a unique image on every frame using a
Scripting, Programming, Coding
traditional frame-by-frame animation tech-
All three of these terms refer to the same thing. All nique. If the dot is filled in, it simply means
you’re doing is writing instructions you want Flash to something is present on the stage at that
follow.The instructions you write when you program frame. Hollow dots mean that nothing is in
for Flash must be very specific and use the ActionScript the keyframe, as might be the case when you
language. want to remove something from the screen
(perhaps a blinking effect where every other
frame is blank).
Timeline Animation
Some programmers have a disdain for the FIGURE 2.2 This timeline shows a keyframe dot in every
timeline. However, it’s important to realize frame.
that animation can be a powerful way to
communicate an idea or suggest a theme.
Flash’s timeline automatically plays from
frame 1 through to the last frame you create.
Naturally, you can write a script to stop() on
any frame you want or choose to create What you draw into each keyframe is up to
everything in just a single frame. Compare you. But be sure to avoid adding a keyframe
the timeline to a flip book that has a different unless there’s going to be something different
picture on each page; the frames in the time- or new in that frame. That is, if you want a
line are like the various pages in the flip title graphic to appear and then go away
book. However, in Flash, only frames that are after a few seconds, you need one keyframe
keyframes display something new. The time- when it first appears followed by 36 frames
line in Figure 2.1 shows a keyframe in frame (not keyframes). On frame 37, you can add
1 followed by additional frames. Something another keyframe in which you delete the
new such as a background image appears on title, thus making the keyframe a blank—and
the first keyframe, but then nothing changes therefore changed—frame.
in that layer for the following 10 frames.
I came up with 36 frames based on the
default frame rate of 12 frames per second
FIGURE 2.1 This timeline shows a keyframe (the circle) at (fps). As a reference, conventional movies use
the 1-second marker, followed by additional frames.
24 fps and television is approximately 30 fps.
You can change the file’s frame rate to make
the animation appear to move faster or
slower by selecting Modify, Document and
changing the fps value there, but that’s not
the only way to make something appear to
30 CHAPTER 2: Producing a Flash Project
move faster or slower in Flash. If you want a motion tweens over shape tweens because
ball to move across the screen more quickly, motion tweens are much simpler to manage
you can simply make the object move a and generally produce smaller files.
bigger distance from frame to frame, thus
Tweening is nice because it can relieve you
making the trip across the screen take less
from the otherwise meticulous work of frame-
time. Realize, too, that using a higher frame
by-frame animation. However, frame-by-
rate can mean more work if you’re drawing
frame animation is often the best option. Just
something unique into each frame.
a few strategically designed frames in your
frame-by-frame animation can often
NOTE communicate a feeling or message much
better than a long, drawn-out tween the
Flash’s frame rate has no impact on external Flash
computer has created. A 1-second animation
video (.flv) files.Their frame rate is set at the time
with 12 carefully created frames playing at
you create the video.
12 fps can look better than 36 frames played
at 36 fps. Plus, your animation will appear
The flip book analogy is great, but you proba- much snappier if you use fewer frames.
bly don’t want to draw every keyframe your- Figure 2.3 shows a simple example in which
self. For this, Flash has tweening. To tween, the frame-by-frame version uses half as
you put an object in one keyframe and then many frames as the motion tween.
add a keyframe to a later frame (not the very
next frame) that contains the object in a
FIGURE 2.3 Sometimes just a few frames in a frame-by-
different location or physical state. Select the
frame animation (bottom) is more effective than a long,
first frame and use the Properties panel to set drawn-out tween (top).
the Tweening values. In the first keyframe,
you tell Flash how to interpolate the in-
between frames so your object ends up looking
like the object in the ending keyframe. You
draw two frames, and Flash tweens the differ-
ence.
There are two kinds of tweens: Motion and
Shape. Motion tweens require you to have a
symbol instance (usually a movie clip) in both
the first and last keyframes. Flash can tween
any property of that clip, including its posi-
tion, scale, rotation, tint, and the new filter The example in Figure 2.3 might be an exag-
effects such as a drop shadow. Shape tweens geration, but my point is that drawing a few
require that you have no symbol instances carefully crafted frames can be more effective
(only shapes) in the two keyframes. Shape than having Flash tween.
tweens can morph between any odd shapes
You probably already know that the Flash
you want, such as between a man and a
timeline supports the concept of layers.
werewolf. Given a choice, you should choose
Flash’s File Structure 31
Objects in higher layers appear in front of depict the first object and its change from the
the objects in lower layers. In addition, first keyframe to the last keyframe; the
special layer options are accessible from the second layer would treat the second object
Layer Properties dialog box shown in Figure the same way. When played together, the two
2.4. You can specify one of the following layers would show the two objects moving in
types of layers: possibly different directions (such as two balls
bouncing). To put one ball in front of the
. Normal layer—Anything you draw in
other, you’d simply change the order of the
a Normal layer (the default) appears in
layers in the timeline.
your final movie as it appears while
authoring.
FIGURE 2.4 Each layer has its own set of properties, as
. Guide layer—You can draw reference defined in the Layer Properties dialog box.
images that won’t export with the
movie.
. Guided layer—A motion tween follows
a path drawn in a Guide layer.
. Mask layer—Objects serve to reveal
what’s in a lower layer that is set to the
Masked layer type. If you wanted to
create a round window port looking out
on the ocean moving by, you’d draw a
circle in a Mask layer.
. Masked layer—You draw the content
you want to reveal only where the
Movie Clip Hierarchy
content of the parent Mask layer After all this talk about the things you can do
appears. For example, you could with multiple frames in the timeline, you
animate an image of the sea in a might be surprised to discover that every
Masked layer as it’s revealed through project in this book uses just one frame! That’s
the circular window shape in the Mask true because there are two ways, other than
layer. using multiple frames, to make something
animate: You can use code to set a movie
clip’s properties such as _x and _y (the x and
To specify which type of layer you are
y coordinates to see it change position on
working with, select Modify, Timeline, Layer
stage), or you can use the timeline contained
Properties.
in every movie clip. Try this: Create a movie
In addition to how layers stack images (and clip by drawing a shape; selecting it; and
arguably more importantly), each layer then selecting Modify, Convert to Symbol.
contains a single animation track. So, if you Then click the Movie Clip option and click
want to make a motion tween with two OK. In place of the shape you drew you’ll
things moving at the same time, you can use have an instance of the clip you just created;
two layers. One layer’s motion tween could
32 CHAPTER 2: Producing a Flash Project
double-click it to edit its contents to see that the cell in frame 20 (underneath the 20 in the
it contains a timeline of its own. timeline but inside your layer) and press F6
to insert a keyframe. Finally, select the first
Notice in Figure 2.5 that the Edit bar shows
keyframe in Animating Wheel and use the
you are inside the movie clip symbol named
Properties panel to select Motion from the
Box. The content of this symbol is simply a
Tween drop-down list. Also, select CW to
drawn shape, the dark square in the lower-
make the Wheel instance rotate once between
left corner (when a shape is selected, the
frames 1 and 20. Return to the main timeline
Properties panel says Shape). The other
and create another instance of the Animating
objects on stage appear faded because,
Wheel symbol by copying the instance on
although you’re inside the Box clip, you’re
stage or by dragging a new one from the
editing it in the context of other objects on
Library panel. Now draw a car body around
the stage. Alternatively, if you open the
the two wheels, select everything, and press
Library and select a symbol to edit, you
F8 to create another movie clip—this time
won’t see anything except that clip’s
called Car. You’ll be able to use an instance
contents.
of the Car symbol to make a motion tween in
What you must take away from this the main timeline, perhaps making the car
overview is that you must always know move across the screen. When you publish it,
where you are in your movie. The Edit bar, not only will the car move, but its contained
shown in Figure 2.5, shows you where you rotating wheels will also move.
are at all times. Because you can nest
instances of other symbols inside a symbol,
the hierarchy can get tricky; however, the Instances Versus Symbols
Edit bar tracks the nesting of the symbols It’s important to understand that, when you make one
and helps you determine just where you are. master symbol, you can create multiple instances of
The Edit bar helps you maintain your bear- that symbol anywhere in the movie except inside the
ings when creating complex symbols such as master symbol itself.The terms symbol and instance are
a car with rotating wheels—you’d have a car not interchangeable. Equally important is the fact that
symbol instance that animates across the a symbol always has a name that appears in the
screen, with its wheels also rotating. First Library. Each instance of that symbol on stage can be
draw a wheel with spokes; select it; and select given an instance name that certainly doesn’t have to
Modify, Convert to Symbol. Then select the match the original symbol’s name. Because you can
Movie Clip option, and click OK. Select the
have many instances of a particular master symbol, the
instance names let you address each instance inde-
instance of the Wheel now on stage and select
pendently using ActionScript. So, you don’t say,“set the
Modify, Convert to Symbol to nest the Wheel
height of the box symbol to 100,” but rather you say,
inside a new symbol; this time, though, call “set the height of the instance of the box symbol with
the movie clip Animating Wheel. Go inside the instance name littleBox to 100.” (The actual code is
the instance of Animating Wheel by double- easier to read: littleBox._height = 100.)
clicking it, where you’ll find an instance of
Wheel. While inside Animating Wheel, click
Flash’s File Structure 33