Tải bản đầy đủ (.pdf) (30 trang)

Flash CS4 Professional in 24 Hours- P11 ppsx

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (1021.93 KB, 30 trang )

ptg
Basic ActionScript
291
Actions are instructions. Flash follows each line of code in sequence. Some
actions are complete pieces of instruction with no additional modifications
on your part. For example, you can add a Stop action, and when Flash en-
counters it, the playback head stops advancing. However, many actions re-
quire you provide additional details called parameters. For example, an
action such as
gotoAndPlay requires you provide the additional detail
about what frame number or frame label you want to go to.
Specifying Actions by Using Parameters
Now you can try out actions and parameters. You see that some actions are
quite simple. The following task is a quick exercise that uses actions and
parameters. After you complete it, we step back to analyze what you did in
the task.
Make an Action That
Loops Part of Your
Movie
TRY IT YOURSELF

In this task, you make the last few frames of an animation loop. Follow
these steps:
1. In a new file, use the Text tool to create a text block containing the
word Welcome. Make sure the text type is Static. Select the block and
convert it to a symbol. Make it a movie clip and name it Welcome
Text.
2. Insert a frame at Frame 19. Add motion tweening. At Frame 1, move
the text offstage to the right. In Frame 19, move the text to the center
of the screen.
3. At Frame 20, choose Insert, Blank Keyframe. Copy the text at Frame


19, and choose Edit, Paste in Place (or press Ctrl+Shift+V) to put it
in Frame 20. Add a frame at Frame 30, and insert a Motion tween.
Use the Properties panel to make the tween rotate one time clock-
wise between Frame 20 and Frame 30. Test the movie. Notice the
whole movie loops over and over. Instead of leaving the animation as
is, you’re going to make the rotation part from Frame 20 to Frame 30
loop forever.
4. You can add actions to any keyframe, but instead of mixing scripts
with your animation, you should make a new layer exclusively for ac-
tions. Name the single layer you currently have Animation, choose
Insert, Layer, and name the new layer Actions. Make sure the current
layer is the one you called Actions. You can tell a layer is selected
when you see a Pencil icon next to the layer’s name. Select Frame 30
in your Actions layer, insert a keyframe by pressing F6, and then ac-
cess the Actions panel by clicking Window, Actions (or press F9).
From the Library of Lee Bogdanoff
ptg
TRY IT YOURSELF

Make an Action That
Loops Part of Your
Movie
Make sure Frame 30 remains selected when you edit the Actions
panel by noting the tab near the bottom of the panel reads Actions:30
and has the keyframe icon, as shown in Figure 16.2. This confirms the
script you’re about to write executes when the playback head reaches
Frame 30.
292
HOUR 16: Basic Interactivity
FIGURE 16.2

The Actions panel is opened right
after Frame 30 is selected so
you can set an action to execute
when the playback head reaches
that frame.
FIGURE 16.3
After you insert gotoAndPlay,
the Actions panel is populated.
5. To insert a gotoAndPlay action, make sure the Actions panel toolbox is
showing, set the filter drop-down to ActionScript 1.0 & 2.0, select
Global Functions, Timeline Control, and then double-click
gotoAndPlay. You should see a gotoAndPlay action added to your
script in the Script pane on the right (see Figure 16.3). Because this
action requires parameters, a code hint appears to help guide you. If it
goes away, click inside the parentheses following gotoAndPlay, and
click the Show Code Hint button.
From the Library of Lee Bogdanoff
ptg
Basic ActionScript
293
As easy as the preceding task was, one thing in particular could make it
better. Consider the amount of work involved if you changed the location
of the keyframes. For example, what if the second keyframe, Frame 20, had
to move to Frame 25? Of course, the initial tween would take longer to play,
and the rotation would be quicker, but the loop would also stop working
properly. To fix it, remember to edit the action in Frame 30 so it reads
gotoAndPlay(25);. You would have to repeat this fix every time you
changed the location of the keyframe where the rotation starts.
There’s a better way. Instead of making the destination of
gotoAndPlay an

explicit frame number, you can change the parameters to make the destina-
tion a named frame label, which is the same for the frame, no matter where it
is located in the Timeline. You use frame labels in the next task.
Make an Action That
Loops Part of Your
Movie
TRY IT YOURSELF

6. You always type any required parameters inside the parentheses. In
this case, type the number 20 because that’s the frame number to
which you want to go and play. Therefore, the finished action in the
script area should read
gotoAndPlay(20).
7. Test the movie with Control, Test Movie as it doesn’t work in the au-
thoring environment. It plays once, and then every time it gets to
Frame 30, it goes back to Frame 20 and plays again. Save or keep
this file open; you need it for the next task.
Use a Frame Label as
the Destination of a
gotoAndPlay Action
TRY IT YOURSELF

In this task, you improve the gotoAndPlay action by supplying a frame la-
bel instead of a frame number. Follow these steps:
1. In the file created in the preceding task, click Frame 20 of the Anima-
tion layer, and insert a keyframe. In the Properties panel under Label,
locate the Name form field. This is where we give Frame 20 a label.
Name this frame Loop Start (see Figure 16.4).
2. Click Frame 30 in the Actions layer, and open the Actions panel.
3. You’re going to modify the

gotoAndPlay line in the Actions panel.
Change 20 to “Loop Start” (with the quotation marks). The final script
should read
gotoAndPlay(“Loop Start”);, as shown in Figure 16.5.
4. Test the movie; it doesn’t look any different from the old version to the
user. Now go back to the Timeline, click Frame 20, and then click and
drag it so Loop Start is now Frame 10.
From the Library of Lee Bogdanoff
ptg
TRY IT YOURSELF

Use a Frame Label as
the Destination of a
gotoAndPlay Action
5. Test the movie again. The animation now loops back to Frame 10,
where you moved the Loop Start keyframe. The power of using a label
as the destination of the
gotoAndPlay action is that you can go back
and move the location of the Loop Start keyframe to any frame you
want, and it still works! Save this file for the next task.
294
HOUR 16: Basic Interactivity
FIGURE 16.4
If you label Frame 20 via the
Properties panel, the destination
of the gotoAndPlay action can
change from an explicit number
(20) to a label name (Loop
Start).
FIGURE 16.5

This new version of the
gotoAndPlay action is better
than the original because the
destination is a frame label.
Frame Actions
In the previous task, you saw how placing one action in a keyframe and
changing its parameters makes the playback head jump to a different
frame. Step back a second and consider what else you’ve learned. Actions
are instructions you want Flash to follow. Actions do things. You can mod-
ify actions by changing their parameters. This is all good information; how-
ever, if actions are instructions, exactly when does Flash follow those
instructions?
From the Library of Lee Bogdanoff
ptg
Making Simple Buttons
295
The answer depends on where you put the actions. It turns out in earlier
versions of Flash you could put actions both in keyframes and on any ob-
ject type, such as button instances, movie clip instances, and components.
Now, in ActionScript 3.0, you can put code only in keyframes. So, as to
when the code triggers, the answer is simple: when the playhead reaches
the frame with the code. In the preceding task, you placed an action in a
keyframe. In that case, the action was executed (that is, the instruction was
followed) when the playback head reached that frame. If you put an action
in Frame 10, it would not be followed until the playback head reached
Frame 10.
With an action in a keyframe, the user doesn’t do anything but wait for the
playback head to reach the appropriate frame to see the action happen. Al-
though this isn’t exactly interactivity, it’s quite powerful. For example, often
it’s useful to place a

stop() action in the first frame so your movie initially
appears paused and doesn’t play until a
play() action is encountered, like
after the user clicks a button. Another example might be when you want to
stop in the middle of an animation. All you need is a keyframe and a stop
action. There are many more examples of keyframe actions, which are good
for when you want something to happen at a certain moment in the anima-
tion, not only when a user clicks a button.
It’s fairly intuitive to understand how the actions you place in keyframes
trigger when the playhead reaches that frame. However, it’s more complex
when you consider that scripts can effectively say, “When this event occurs,
do this action.” For example, you might want an animation to start when
the user clicks a button. In that case, your code is waiting for a mouse press.
It’s easiest to always ask yourself, “What do I want to do, and when do I
want to do it?” If you want something to happen when the keyframe is
reached, put the code in that keyframe. If you want to wait for some event,
you need to learn about listening for events. We get to that right after you
learn how to make the most basic of event triggers—the simple button.
Making Simple Buttons
Before we start, you’re going to take a short break from ActionScripting to
learn how to create a button. There are only a few ways for the user to in-
teract with your movie. Clicking a button is the easiest and most common.
Other events users can trigger include key presses, such as pressing the ar-
row keys on their keyboards. You can create buttons and make them look
cool without any ActionScript. Nothing happens when the user clicks unless
From the Library of Lee Bogdanoff
ptg
TRY IT YOURSELF

Make a

Simple Button
In this task, you make a simple but useful button. Follow these steps:
1. In a new file, draw an oval or a rectangle that becomes your button.
2. Use the Selection tool to select the entire shape.
3. Convert the shape to a symbol by selecting Modify, Convert to Sym-
bol (or press F8).
4. Name the symbol MyButton; make sure you select the button behav-
ior, and then click OK.
5. Test your movie by using Control, Test Movie (or press Ctrl+Enter),
and notice the way your mouse cursor changes when you place it over
the button, as shown in Figure 16.6.
6. Close the
.swf you’re testing, so you can edit the button. Double-click
the instance on the Stage, and you are taken inside the MyButton
symbol. Notice the Timeline looks different. It has only four frames,
and they’re named to match the four possible button states. It should
look like Figure 16.7.
296
HOUR 16: Basic Interactivity
you write ActionScript to respond to that event. We start by creating the
buttons, and then deal with the ActionScript in the next section.
It’s easy to make a button because it’s another symbol type like Movie Clip
or Graphic. Draw a shape, select it, choose Modify, Convert to Symbol, and
then select Button. When you test the movie, the cursor changes when you
roll over the button, indicating to the user that the button is clickable. Noth-
ing happens yet, but we get to that in the next section, “Listening for
Events.”
On the surface, a Button symbol is like a Movie Clip. The main characteris-
tic of a Button symbol is you have the opportunity to create two additional
states for it. One is for when the user first rolls over the button and another

for when he clicks on the button.
Let’s create a button that takes advantage of button states.
FIGURE 16.6
Any shape can be used as a
button. The user’s cursor
changes to a hand when it’s
over the button.
From the Library of Lee Bogdanoff
ptg
Make a
Simple Button
TRY IT YOURSELF

7. You create new keyframes for the Over and Down states. To do this,
click the Over frame, and insert a keyframe. Select the Free Trans-
form tool, and then scale the contents of the second frame (the Up
state) by making it a tad larger.
8. Select the third frame (the Down state), and insert another keyframe.
Select the button’s shape in the new keyframe (Frame 2), and nudge it
two pixels down and two pixels to the right.
9. Test the movie. This time the button should grow when you roll over it;
click, and move down and to the right when you click it.
Making Simple Buttons
297
FIGURE 16.7
Four frames for the four states of
a button are inside a button.
A few details about buttons are worth noting. First of all, you don’t have to
create a different graphic in each state of the button. What might seem odd
is you don’t need to have frames for the different states. Even though Flash

tries to go to the Over state when users roll over your button, if nothing
new is in that frame, they see what’s in the Up state.
In addition to Up, Over, and Down, there’s another state called Hit. The Hit
state is never visible to the user. It defines where the user must position her
cursor to show a button’s Over state or where she must click to see the but-
ton’s Down state. Imagine you had a doughnut-shaped button. If you didn’t
NOTE
The Four States
A button state is the way the
button looks at a particular
moment in time. The Up state
contains the appearance of
the button in its normal state.
The Over state contains the
look for when the user hovers
his cursor over the button.
Down is the state when the
user clicks. Hit is a special
state in which you define what
portion of the button you in-
tend to be clickable. The user
never sees the graphic you put
into the Hit state, but the
shape of that graphic is what
the user must “hit” to trigger
the button.
From the Library of Lee Bogdanoff
ptg
298
HOUR 16: Basic Interactivity

set a Hit state, the user wouldn’t be allowed to click anywhere in the hole
(similar to Figure 16.8). However, if you inserted a keyframe and drew a
solid circle (no doughnut hole) in the Hit frame, the user could click any-
where within the solid circle. This can also be useful when you want a
small button, but you don’t want to frustrate the user by requiring her to
have the precision of a surgeon. It’s usually a good idea to make the Hit
state big enough to easily click even if that means that it’s bigger than the
button.
In the task, “Make a Simple Portfolio Viewer,” at the end of this hour, you
make a button with nothing in the Up, Over, or Down states. You draw a
shape in only the Hit state. This creates an invisible button, which means
you don’t see anything normally, when you roll over it, and when you click
it. Even though you don’t “see” the shape in the Hit state, that shape
makes the button clickable. While you’re working in Flash, invisible but-
tons show up as a semitransparent cyan tint, so you can resize and position
them as needed. The advantage of an invisible button is you can use it on
top of any other graphic. For example, you might have a large photo on
which you want the user to be able to click on individual spots. If you did-
n’t use invisible buttons, which can be placed over other graphics, you’d
have to cut up the image and make a new button for each slice. Figure 16.9
shows an example where several round invisible buttons are used on top of
a photograph.
FIGURE 16.8
Changing the shape contents of a
button’s Hit state affects what por-
tion is clickable.
FIGURE 16.9
Invisible buttons enable you to
make any area clickable rather than
make a new button for each spot.

From the Library of Lee Bogdanoff
ptg
Listening for Events
299
Another important note about buttons: You can put anything you want into
those three keyframes (Up, Over, Down). You get only one keyframe for
each, but that doesn’t mean you can’t put more than one Movie Clip sym-
bol in that frame. If you create a Movie Clip that contains a 10-frame anima-
tion and then place that Movie Clip in the Over state for a button, the user
sees that animation play and continue to loop when her mouse is over the
button. In this way, you can make animated buttons.
Now that you have created your own button, you have something to click
during the ActionScript exercises that follow. The simple buttons you cre-
ated are not the only kinds of buttons in Flash. These buttons (the ones you
created by selecting Modify, Convert to Symbol) are officially called Simple
Buttons. As you learn next hour, buttons are also available from the Com-
ponents panel, the so-called UI Components. The primary difference is Sim-
ple Buttons are easy to create and support in only the four states. Some of
the UI Components support additional states such as Disabled or Checked
and Unchecked. Don’t worry about that for now; keep in mind that Simple
Buttons enable you to create custom buttons quickly.
Listening for Events
You’re about to learn the basics of writing ActionScript that triggers only
when a specific event occurs. Remember in the earlier exercise, “Make an
Action That Loops Part of Your Movie,” the ActionScript you put in the last
keyframe told Flash to go back and play from Frame 20. Every time the
playhead reached that last frame, it looked at the code and executed your
ActionScript. Now you see how to write ActionScript that waits for an
event—namely, when the user clicks a button.
NOTE

No Buttons in Buttons
You can put nearly anything into
a button. The only exception is
another button. Buttons nested
inside of each other fail to re-
spond to any ActionScript.
Add Buttons to an An-
imation to Stop and
Continue Playback
TRY IT YOURSELF

In this task, you add buttons that enable the user to stop and continue the
animation from the task earlier this hour. Follow these steps:
1. Either use the file created in the task, “Make an Action That Loops
Part of Your Movie,” or make a new Flash File (ActionScript 3.0) with a
motion tween over several frames. Make sure you can see something
moving while the animation plays. If you’re using the old file, make
sure the publish settings are set for ActionScript 3.0; select File,
Publish Settings, click the Flash tab, and then ensure the ActionScript
version dropdown is set to ActionScript 3.0.
From the Library of Lee Bogdanoff
ptg
300
HOUR 16: Basic Interactivity
TRY IT YOURSELF

Add Buttons to an An-
imation to Stop and
Continue Playback
2. Insert a new layer for the buttons. You don’t want to place buttons in

the layer that has the animation; that would affect the tween. Name
the new layer Buttons.
3. Into the new Buttons layer, draw a rectangle that becomes a button.
Select it, and then convert it to a symbol by pressing F8. Name it
MyButton, and make sure the behavior is set to Button.
4. You’re going to need two buttons, so either copy and paste the in-
stance that is already on the Stage or drag another instance of the My-
Button symbol from the Library onto the Stage in the Buttons layer.
Apply a Tint color style to each instance—one red for Stop and one
green for Play. As you recall, you do so by selecting the button in-
stance on the Stage, using the Properties panel to select Tint from
the Color drop-down list, and then selecting a color and percentage.
5. Give each button a memorable instance name:
stopButton for red
and
startButton for green. Like adding a label, you use the Properties
panel to set the instance names. Select them each in turn, and type
in the name for each in the first text box near the top of the Properties
panel. The instance names are necessary, so you can specify what
should happen when the user clicks a button.
6. Now you’re going to write the code in a keyframe. The code tells
Flash,, “When users click stop, Flash stops, and when they click start,
Flash plays.”. Select the first keyframe in the Buttons layer, and open
the Actions panel. Write the following code:
stopButton.addEventListener ( MouseEvent.CLICK, myStopHandler )
function myStopHandler( evt ){
stop()
}
Translating this code: The first line says the stopButton instance
should broadcast the

CLICK event to the homemade function called
myStopHandler. That is, any time the user clicks the stopButton in-
stance, it triggers the code inside the
myStopHandler function. A
homemade function always begins with the word function, followed by
the name of your function; in this case,
myStopHandler is followed by
an opening and closing parenthesis, which is followed by an opening
and closing curly brace ({}). Exactly what you put between the two curly
braces is up to you. You can put one line of code or 1,000 lines of
code. In this case, we put the Timeline action called
stop().
7. See whether it works so far. Select Control, Test Movie. Click the
Stop button, and the animation should stop. Close the
.swf you’re
testing to add a listener for the
CLICK event on the Start button.
From the Library of Lee Bogdanoff
ptg
Listening for Events
301
The ActionScript in the previous task can seem overwhelming if you’re new
to programming. The good news is the way you handle events (that is, the
way you write code that executes only after an event occurs) is consistent.
As soon as you learn a few basics, you can extrapolate those basics to more
advanced applications, and the ActionScript begins to look more familiar.
Understanding Event Handling
Although the term event handling could be new to you, we’re talking about
how you write code that reacts to various events, like when a user clicks a
button. Other examples include an event that occurs when a sound reaches

its end or when a key is pressed. Before you code anything, you always
need to think about what you want to do, and when you want to do it. The
“when” is the event, and we’re going to explain how you capture such
events.
The way you write ActionScript to handle events involves two parts. First,
there’s an object that broadcasts events—in this case, the button. You iden-
tify both the object and the event you want to capture. Different object
types can broadcast different events. The code you saw in the previous ex-
ercise used a command called
addEventListener() to send the CLICK event
to the homemade function, and even more specifically, the code inside that
homemade function. In the preceding task, that’s the
play() or the stop()
code. The second part, you always need the code that handles the event,
which is the destination where the events need to be broadcast. Think of it
Add Buttons to an An-
imation to Stop and
Continue Playback
TRY IT YOURSELF

8. Go back to the first frame in the Buttons layer to add more code. Fol-
lowing the code that you have, add the following code:
startButton.addEventListener ( MouseEvent.CLICK, myStartHandler )
function myStartHandler( evt ){
play()
}
9. There’s not much new here. This time you’re sending the CLICK
events on the start button to the myStartHandler function that, in
turn, triggers the
play() action.

10. Test the movie, and you find when you click the buttons, the movie
plays and stops.
From the Library of Lee Bogdanoff
ptg
302
HOUR 16: Basic Interactivity
this way: The button triggers all kinds of events, like the mouse rolling
over, the mouse click, and the mouse release. Like a tree falling in the forest,
if no one is listening, nothing really happens. The
addEventListener()
code listens for you and connects the event to the code you want to execute
when the event occurs.
Every time you write
addEventListener(), it looks consistent. It’s always
myObject.addEventListener(“someEvent”, myHandler);
You don’t say myObject. You replace that with the instance name of the ob-
ject you want to handle events. You don’t say someEvent, but you replace
that with the specific event. You also replace myHandler with the name of a
homemade function, which must always follow this form:
function myHandler ( evt ) {
//any code you want
}
Notice function is used verbatim. You can be creative with the function
name, shown as myHandler, but don’t start with a number, and don’t use
spaces in the name. The part that’s really important is what you put in be-
tween the curly braces. Right now we have a comment that reads: //any
code you want. You replace that with one or more lines of code.
As we mentioned, replace someEvent with a specific event that the object
type supports. In the case of buttons, you could replace that with Click or
mouseDown, among other values. Recall in the last exercise you used the

seemingly more complex value
MouseEvent.CLICK. That’s called a constant,
and it’s a built-in feature of ActionScript that ensures you don’t make syn-
tax errors. You can use Click or you can use
MouseEvent.CLICK, and both
work the same way. You can probably guess that if you used clickTime, it
wouldn’t work, but it would fail silently, meaning you could spend a long
time trying to hunt down the problem. However, if you tried
MouseEvent.CLICK_TIME, Flash would immediately squawk at you when
you tested the movie because of a compile-time error. Remember, the pa-
rameter needs to be a string that the object type supports. Using a literal
string where you type it out between quote marks is risky because you
never get a compile-time error if you spell something wrong. However, by
using a constant, you never get far without a warning. As soon as you type
the period after
MouseEvent, you see a code completion drop-down from
which you can simply select the event name you had in mind, as shown in
Figure 16.10.
From the Library of Lee Bogdanoff
ptg
Listening for Events
303
Properties and Methods
Event handling helps you tackle the “when” in “What do you want to do,
and when do you want to do it?,” but we haven’t looked far into the
“what.” In the previous tasks, you’ve seen three pieces of ActionScript:
stop(), play(), and gotoAndPlay(). Those are all called methods. They’re
processes or things that do something. The
addEventListener() is also a
method but it’s different because you don’t get an immediate visual result

the way you do when triggering
stop() or play(). Another difference is in
the way you used the
addEventListener() method. You didn’t say

addEventListener(),” you said “someObject.addEventListener()” with
someObject being the actual button instance name. The point is that meth-
ods can perform their action on a specific object. The form to trigger meth-
ods is always
someInstance.someMethod()
If you go back to the first two tasks where we looped part of an animation
with
gotoAndPlay() and then made the entire animation stop() or play(),
no instance names were ever used. In those cases,
stop() is interpreted by
Flash as meaning, “Stop the current Timeline.” This is important if you
have a Movie Clip instance onstage, and it contains multiple frames, con-
tinuing to play even if you encounter the ActionScript
stop(). If you want
to address a specific Movie Clip instance and make it stop, you use the
form
someInstance.stop(). If the instance name of your Movie Clip is box,
use
box.stop(). You need to only name your instances if you intend to ad-
dress them with ActionScript. The part that’s tricky is you need to find the
methods that are supported by the object type. If you’re trying to tell a
Movie Clip instance to do something, you use one of the methods of Movie
Clips, such as
stop() or play(). However, if you have an instance of a
video, different methods might be available. In fact, videos use a method

called
seek(), which you can think of as similar to gotoAndPlay(). Videos
and Movie Clips support different methods. It’s consistent however; you al-
ways use
someInstance.someMethod().
FIGURE 16.10
The code completion drop-down
helps you select the appropriate
event name.
From the Library of Lee Bogdanoff
ptg
304
HOUR 16: Basic Interactivity
There’s another powerful way to make the objects onstage change in Flash,
and it’s actually simpler than triggering methods. Remember, methods are
processes or things that objects can do. Properties are a similar, but simpler
concept. Properties are attributes that each Movie Clip instance can have or
maintain independently. For example, two Movie Clips could have a differ-
ent value for their
width property. Even two instances of the same Movie
Clip symbol can have different widths. The
width property is one of many
properties. Other properties of Movie Clip instances include
x (horizontal
position),
y (vertical position), and rotation. The great news is you always
use the same syntax to access properties:
someInstance.someProperty
For example, you could say myMovieClip.x. If you step back and think
about the meaning of

myMovieClip.x, it doesn’t really mean much. If you
intend to change the value of a property, you use this form:
someInstance.someProperty = someValue
For example, to move a Movie Clip instance named myMovieClip, 100 pix-
els from the left edge of the stage, you’d say
myMovieClip.x = 100
In this example you’re setting the x property to 100. You can read the equals
sign as “is now equal to,” or in English, “
myMovieClip’s x is now equal to 100.”
Like methods, the available properties vary based on object types. Buttons,
Movie Clips, and Videos all have a property for
x, but only Videos have a
totalTime property, which contains the total number of seconds in the video.
One last point before you get to try all this out on some real tasks: Remem-
ber, if you want to only get the value of a property you still go back to the
form
someInstance.someProperty. For example, if you have two instances
onstage named
box1 and box2, you can align them both by using
box1.x = box2.x
Notice it’s box1 that is moving so its x property is equal to box2’s. The fol-
lowing exercise should help solidify your understanding of ActionScript.
ActionScript Application
The task that remains this hour gives you a chance to practice what you’ve
learned so far, but it’s also a practical task.
TIP
Learning Without
Memorizing
It’d be cool if you could memo-
rize every last method and prop-

erty in ActionScript, but that’s
not practical. Instead, it’s best if
you step back and think about
the task you’re trying to achieve,
and write it out using your own
words. This is called
pseudocode. If you can write out
the instructions for the task at
hand using your own words, then
the process of translating to ac-
tual ActionScript becomes me-
chanical. It’s not easy to “think
in ActionScript.” So, start by
thinking of what you want to
achieve. Compare this to how
you might mail a letter when
traveling in a foreign country.
You might not know the word for
“post office,” but you can proba-
bly assume they have such a
place; it’s just a matter of find-
ing the correct word. This is sim-
ilar to working in ActionScript
and trying to change the volume
for a video. You might not know
whether the property is called
soundLevel, volume, or
loudness, but you can probably
bet there is a way to change the
sound level. If you map out what

you want to achieve, you can
use your own words, and then
slowly replace that pseudocode
with actual ActionScript as you
hunt down the language syntax.
From the Library of Lee Bogdanoff
ptg
Listening for Events
305
Make a Simple Port-
folio Viewer
TRY IT YOURSELF

In this task, you make a tool that enables you to view different images.
Most of the work in this task revolves around structuring the file and not
so much writing ActionScript.
1. Create a new Flash, and be sure to select the first option (ActionScript
3.0).
2. Draw a rectangle to hold the content. If you plan to import photos later,
you should make this rectangle big enough to hold those images.
3. Select the entire rectangle, and convert it into a Movie Clip by choos-
ing Modify, Convert to Symbol (or press F8). Make sure you select
the Movie Clip behavior as it might be set to Button from a previous
task. Call this symbol Content.
4. Double-click the instance of Content, so you can go inside it to edit its
contents. Click Frame 4, and press F5 to insert frames. This layer is
the background. Name this layer Background.
5. Insert a new layer by choosing Insert, Timeline, Layer, and drag this
new layer above the Background layer. Name this layer Photos, and
then select all four frames in the Photos layer. A quick way to select all

frames is to click the layer name. With all frames in the Photos layer
selected, press F6 to convert all the frames into keyframes at once.
6. Go to Frame 2 of the Photos layer, and draw a rough A. You can re-
place this later with an imported photo. Go to Frame 3, and draw a B;
go to Frame 4, and draw a C. If you know you are replacing this con-
tent layer, draw the rough A, B, and C to make testing easier. The in-
side of the Content Movie Clip should look like Figure 16.11.
FIGURE 16.11
The Timeline of the Content
Movie Clip has two layers: one
for the background and one with
keyframes for each piece of
content.
From the Library of Lee Bogdanoff
ptg
306
HOUR 16: Basic Interactivity
TRY IT YOURSELF

Make a Simple
Portfolio Viewer
7. You’re finished with the Content Movie Clip, so return to the main
Timeline by clicking Scene 1.
8. Select the instance of the Content Movie Clip, and use the Properties
panel to give it the instance name
myContent. This enables you to ad-
dress it in your ActionScript code.
9. It’s time to add three buttons to enable the user to jump to any one of
the three frames (2–4) inside the
myContent instance. Rather than

make three new buttons, you make a single invisible button and place
three instances on top of three thumbnails of the content. Before
making the invisible button, however, you need to create the thumb-
nails the user sees. It doesn’t really matter how you create the thumb-
nails because you are putting invisible buttons on top of it. You could
draw shapes, import images, or use Movie Clips. We show you an in-
teresting trick, although it might not be applicable to every project.
10. For the thumbnails, drag three more instances of the Content symbol
from the Library onto the Stage. Select all three, and use the Proper-
ties panel to change the instances’ behavior from Movie Clip to
Graphic. Use the Free Transform tool to resize them to a smaller, con-
venient thumbnail size (maybe one-fourth of their original size). Posi-
tion these three instances vertically on the left side of the main
myContent instance.
11. You don’t need to give these three thumbnails instance names. In fact,
you can’t because their behavior is Graphic. Use the Properties panel
to individually set each instance, so it displays the content users navi-
gate to when they click. Graphic symbols have a handy feature where
you can set their First Frame. Select the first thumbnail, use the Proper-
ties panel to ensure the Options for graphics drop-down reads Single
Frame, and change the First field to read 2. You should see the thumb-
nail display that rough A you created inside the master Content Movie
Clip.
12. Use the same technique described in step 11 to change the second
thumbnail to display the B (set its first frame to 3). Then, set the last
thumbnail to display the C (first frame goes to 4).
13. Finally, to make the invisible button, use the Rectangle tool to draw a
square off to the side that’s the same size or bigger than one of the
thumbnails. Select the drawn square, and convert it to a button by
choosing Modify, Convert to Symbol (or press F8 and choose

Button). You can name it Invisible. Click OK, and you see this button
is far from invisible. That’s because the square you drew is in the Up
state. Double-click the instance of Invisible, so you can move the
shape into the Hit state. Click once on the Up keyframe in the Invisible
From the Library of Lee Bogdanoff
ptg
Listening for Events
307
Make a Simple Port-
folio Viewer
TRY IT YOURSELF

button, and then click and drag to move the keyframe to the Hit state.
The button’s Timeline should look like Figure 16.12.
14. Return to the main Timeline by clicking Scene 1, and you see the Invisi-
ble button is semitransparent cyan. Create two more instances, and
place the three invisible button instances on top of the three thumb-
nails.
15. Use the Properties panel to individually set the instance names for the
three buttons as follows:
buttonA, buttonB, and buttonC. The code is
basically going to say, “When users click
buttonA, make the content
movie clip go to Frame 2; when users click
buttonB, make the content
go to Frame 3,” and so on. There’s one last touch worth adding.
16. Let’s highlight the button the user selects. Homemade buttons don’t
have a built-in highlight feature. Rather, you can draw a rectangle or
check mark that moves to appear on top of the most recent button
the user clicks. To do this, use the Brush tool to draw a check mark.

Change the Stroke to something thick. Select this check mark, and
convert it to a Movie Clip named Highlight. Make sure you select the
Movie Clip option in the Convert to Symbol dialog. Use the Proper-
ties panel to name the instance
highlightClip. Finally, place the
highlightClip instance on top of one of the thumbnails, and then
use the arrow keys to move the highlight up until it’s offscreen. This
way the user doesn’t see it at the beginning, and you need to change
only the vertical location to align with whichever button the user
clicks.
FIGURE 16.12
An invisible button’s Timeline has
three blank frames and graphics
in its Hit state. The faded con-
tents shown are on the main
Stage—not in the button.
From the Library of Lee Bogdanoff
ptg
308
HOUR 16: Basic Interactivity
Stop for a second and catch your breath! We take a closer look at this code,
but first, look it over yourself. See if you can figure out what each line is do-
ing before reading ahead. Some of it should be obvious, but some isn’t. Don’t
worry; give it a try, and you’ll be surprised by how much you understand.
Figure it out? The first line triggers the
stop() method on the myContent in-
stance. Without this, the
myContent instance would be looping at the start.
The next three lines use
addEventListener() to send the CLICK event from

each of the three button instances (
buttonA, buttonB, and buttonC) to the
three homemade functions (
clickA(), clickB(), and clickC()). Those three
functions look nearly identical. The code inside the three custom functions
does the same two things: First, it sets the
highlightClip’s y property
equal to the respective button’s
y property, and second it triggers the
gotoAndStop() method on the myContent instance to display the appropri-
ate frame number.
This code is created to be useful and not terribly complex. In fact, it’s based
on what you learned earlier this hour. That’s not to say it’s the most adapt-
able code possible. Every additional button you create requires another
addEventListener() and another function (clickD, clickE, and so on). After
you become more skilled with ActionScript, adapting this code to be more
efficient will be an easy task for you. Look at how far you’ve come!
TRY IT YOURSELF

Make a Simple
Portfolio Viewer
17. The structure was the hard part. The ActionScript part looks simple in
comparison. Select the first keyframe in your file, and enter the follow-
ing code into the Actions panel:
myContent.stop()
buttonA.addEventListener( MouseEvent.CLICK, clickA );
buttonB.addEventListener( MouseEvent.CLICK, clickB );
buttonC.addEventListener( MouseEvent.CLICK, clickC );
function clickA( evt ){
highlightClip.y = buttonA.y;

myContent.gotoAndStop(2);
}
function clickB( evt ){
highlightClip.y = buttonB.y;
myContent.gotoAndStop(3);
}
function clickC( evt ){
highlightClip.y = buttonC.y;
myContent.gotoAndStop(4);
}
From the Library of Lee Bogdanoff
ptg
309
Summary
Summary
This hour touched on the fundamental things you can do with Action-
Script. You have learned how code can be placed in a keyframe to execute
when that frame is reached. You’ve also learned how to set up event han-
dlers so code executes only when the specified event occurs.
We got into some advanced topics such as triggering methods and setting
properties. The content covered this hour is a giant first step into an even
bigger topic of ActionScript. Although a lot of new material has been intro-
duced here, we presented the topics in a way that is consistent with more
advanced topics that you’ll explore as you grow. It was a lot to learn, but
you’ll see the similar code tasks coming up again and again as you develop
your ActionScript skills.
Q&A
Q. I put the action gotoAndPlay(5) in the last frame of my movie, and I
swear the movie never reaches the last frame because I have some
text that is supposed to appear briefly on the Stage on just that last

frame. It works only if I put the graphics one frame before the
gotoAndPlay action. Why?
A. This is a critical concept: Frame actions are executed before the on-the-
Stage graphics of that frame are displayed. If your action says to go to
another frame, it goes to the other frame before it draws graphics on
the Stage.
Q.
Why does my movie loop, effectively doing a gotoAndPlay(1) on the
last frame, even though I haven’t put any actions in it?
A. The option to automatically loop is set by default when you test a movie
and when you publish a movie. While testing, you can uncheck the op-
tion to loop from the Control menu of the Flash Player, not the Control
menu of the Flash authoring program. If you turn this off, you most cer-
tainly don’t see the movie loop unless you include an action to make it
loop. Normally, you don’t need a
stop action at the end of your Time-
line; if you simply uncheck the Loop option when you publish, the movie
automatically stops on the last frame.
Q.
Which action do I use to create a commercial video game?
A. We are taking baby steps first. It’s amazing the kind of powerful things
you’ve done this hour. It’s going to take a lot more work before you’re
cranking out video games; although you can create amazing games by us-
ing Flash, it takes a lot of work. For now, we’re just laying the foundation.
From the Library of Lee Bogdanoff
ptg
310
HOUR 16: Basic Interactivity
Workshop
The Workshop consists of quiz questions and answers to help you solidify

your understanding of the material covered in this hour. You should try to
answer the questions before checking the answers.
Quiz
1. Where can buttons be placed in your movie?
A. In the main Timeline only.
B. Anywhere you want: in the main Timeline or a Movie Clip’s
Timeline, just not inside another button.
C. Anywhere you want, including inside other buttons.
2. What is an action?
A. Anything that moves on the Stage.
B. An instruction snippet that tells Flash what to do.
C. What programmers call a function.
3. What is a great technique to make coding a little easier?
A. Copy the code out of this book.
B. Get a friend to help.
C. Use pseudocode.
4. What’s the difference between a method and a property?
A. A property is the current value for an attribute, and a method is
more involved because it does something.
B. They’re the same; property is the old name for method.
C. You lost me back on the first page of this hour.
From the Library of Lee Bogdanoff
ptg
311
Workshop
Quiz Answers
1. B. Or possibly C is correct if you don’t mind that the button doesn’t
work. We just wanted to remind you not to put buttons inside buttons.
2. B. Action is a generic term, so Answer B is the best of these definitions.
3. C. If you can organize your ideas using pseudocode, it’s a matter of

mechanics to convert it to real code. Conversely, if you can’t organize
your ideas, you can’t build anything because it’s too vague.
4. A. Another way to tell them apart is that methods always include
parentheses. The parentheses can hold parameters, though not all
methods require them. If you answered C, please note you can still do
tons of cool Flash stuff without ActionScripting.
From the Library of Lee Bogdanoff
ptg
This page intentionally left blank
From the Library of Lee Bogdanoff
ptg
WHAT YOU’LL LEARN IN
THIS HOUR:
. How the common user
interface components
can help standardize
your application
. How to populate com-
ponents with cus-
tomized data
. How to make compo-
nents trigger your own
ActionScript
Last hour you had the option to learn some programming. You might have
chosen to skip it because it covered material that was more technical than
you’d prefer. If you did read it, you might have wished it was more techni-
cal. This split is natural. Some people like to express their creativity by solv-
ing puzzles, whereas others like more artistic endeavors. One of the great
things about Flash is that it can appeal to both types of people. Compo-
nents are a great example of this.

A component is a version of a Movie Clip that has programming code built
into it so a nontechnical person can use it without having to know how it
works. Anyone can use a component. Depending on the features of the
component, it can do some pretty impressive things. Despite the simplicity
that components offer, you still have to invest some time to learn how com-
ponents work. The features the components provide are so advanced that
it’s worth the investment to learn.
This hour you learn both which components are available and the basics of
how to use them. Next hour you learn more advanced topics and many
more practical uses for components.
What Is a Component?
We described components as movie clips with code in them. However, a
Movie Clip with actions inside doesn’t automatically become a component.
A Movie Clip symbol becomes a component when the component devel-
oper identifies parameters that can be set differently for each instance. It’s
similar to how you can scale or tint any Movie Clip. In the case of compo-
nents, you can set other properties in addition to the scale and tint. For ex-
ample, you can set the label on each instance of a Button component to
change the word that appears on the button. The most common compo-
nents are used for user interface (UI) elements such as buttons and menus.
However, a component is a clip with code and the capability to have initial
values set differently for each instance.
HOUR 17
Introducing Components
From the Library of Lee Bogdanoff
ptg
TRY IT YOURSELF

Manually Populate
the ComboBox

Component
Later this hour you build on this task, but in this task, you populate the
component. Follow these steps:
1. Create a new Flash file, be sure to select the first one listed (Action-
Script 3.0), and open the Components panel by selecting Window,
Components. It’s possible to install sets of components, so make
sure the User Interface components section is fully expanded, as
shown in Figure 17.2.
2. Drag the ComboBox component onto the Stage as if you were dragging
an instance from the Library. You can use the Free Transform tool to
change its width without causing it to distort, but don’t rotate or skew
it. With the instance on the Stage still selected, open the Component
Inspector panel.
3. Before you populate the parameters, give this instance a unique name
so later you can access it by using ActionScript. Name the instance
myComboBox. You see this instance name reflected near the top of the
Component Inspector panel.
4. In the Component Inspector, select the line
dataProvider. Click the
Magnifier button at the right of this line (see Figure 17.3).
5. In the Values dialog box that appears, click the Plus button, and then
replace the text label0 that appears in the right column with Adobe.
This is the first item to appear in the ComboBox component. For each
item, you have a label, which the user sees, and an optional slot for
314
HOUR 17: Introducing Components
You typically follow this order to use a component:
1. Place it on the Stage.
2. Populate it with data. For the Button component, for example, you
might only change its label.

3. Define the ActionScript that gets triggered when the component’s event
fires, such as how you want to handle the
click event for the Button
component.
4. Place additional components that might work together, like the
RadioButton component, of which you always want two or more.
We spread all these steps into separate tasks in this hour. The first series of tasks
uses the ComboBox component. This is basically a drop-down menu from which
the user can select any option, as shown in Figure 17.1. As with any component,
you can define exactly how the ComboBox component is populated (that is,
what’s listed in the drop-down list), as well as how it behaves (for example, what
it does when the user makes a selection). You do that in the next task.
FIGURE 17.1
You can use the ComboBox compo-
nent to enable your users to make
selections.
FIGURE 17.2
Make sure the User Interface
components are fully expanded.
From the Library of Lee Bogdanoff
ptg
Manually Populate
the ComboBox
Component
TRY IT YOURSELF

data. In the data field, type . Later you use
ActionScript to grab that value and hyperlink to it. Repeat the process
of clicking the plus button to create two more items—one for Mi-
crosoft and another for Sams. The data you enter for Microsoft should

be , and the data you enter for Sams is
. You can click any value you have
created and move it up or down in the list by pressing the arrow
buttons. The completed Values dialog should appear as shown in
Figure 17.4. Click OK when you’re finished.
6. Test the movie, and you see the ComboBox component reflects the
values you added and enables you to make selections. This is a so-
phisticated piece of code, and all you had to do was provide unique
data. The only problem is nothing happens when the user selects an
item because you don’t have any code that reacts to the event of the
user changing the ComboBox. You resolve all this in the next task,
“Populate the ComboBox Component by Using ActionScript,” by set-
ting up an event listener much like you first did last hour. Keep this
file for the next exercise.
What Is a Component?
315
A common attribute of many components is the way they can contain a
data provider—specifically, a list of labels paired with data. The user sees
the labels, but only your ActionScript can see the data. The data provider
gives you a convenient place to store additional details that the user doesn’t
need to see. In the case of the ComboBox component from the preceding
task, the labels are what the user sees onscreen, and the data is the actual
web addresses to which we jump. Let’s do that now.
FIGURE 17.3
You populate the ComboBox’s
dataProvider property by first clicking the
Magnifier button in the Parameters panel.
FIGURE 17.4
The completed dataProvider Val-
ues panel contains labels and data

values for three websites.
From the Library of Lee Bogdanoff

×