For example, an action such as gotoAndPlayrequires you provide the additional detail about what frame number or frame label you want to go to.. Select Frame 30 in your Actions layer, ins
Trang 1Actions 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 gotoAndPlayrequires 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
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
conver t it to a symbol Make it a movie clip and name it Welcome
Text
2 Inser t 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 inser t 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 par t 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, inser t a keyframe by pressing F6, and then
ac-cess the Actions panel by clicking Window, Actions (or press F9)
Trang 2TRY IT YOURSELF
▼
Make an Action That
Loops Part of Your
Movie
Make sure Frame 30 remains selected when you edit the Actionspanel by noting the tab near the bottom of the panel reads Actions:30and has the keyframe icon, as shown in Figure 16.2 This confirms thescript you’re about to write executes when the playback head reachesFrame 30
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 inser t gotoAndPlay,
the Actions panel is populated.
5 To inser t a gotoAndPlay action, make sure the Actions panel toolbox isshowing, set the filter drop-down to ActionScript 1.0 & 2.0, selectGlobal Functions, Timeline Control, and then double-click
gotoAndPlay You should see a gotoAndPlay action added to yourscript in the Script pane on the right (see Figure 16.3) Because thisaction requires parameters, a code hint appears to help guide you If itgoes away, click inside the parentheses following gotoAndPlay, andclick the Show Code Hint button
Trang 3As 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 gotoAndPlayan
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
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 ever y 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
In this task, you improve the gotoAndPlayaction 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 inser t a keyframe In the Proper ties 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 gotoAndPlayline 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 Star t is now Frame 10
Trang 4FIGURE 16.4
If you label Frame 20 via the
Proper ties panel, the destination
of the gotoAndPlay action can
change from an explicit number
(20) to a label name (Loop
Star t).
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 andchanging its parameters makes the playback head jump to a differentframe Step back a second and consider what else you’ve learned Actionsare 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
Trang 5The 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
Trang 6In 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 Conver t the shape to a symbol by selecting Modify, Convert to bol (or press F8)
Sym-4 Name the symbol MyButton; make sure you select the button ior, and then click OK
behav-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 overthe button, as shown in Figure 16.6
6 Close the .swfyou’re testing, so you can edit the button Double-clickthe instance on the Stage, and you are taken inside the MyButtonsymbol Notice the Timeline looks different It has only four frames,and they’re named to match the four possible button states It shouldlook like Figure 16.7
you write ActionScript to respond to that event We start by creating thebuttons, 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, andthen select Button When you test the movie, the cursor changes when youroll 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 forEvents.”
On the surface, a Button symbol is like a Movie Clip The main tic of a Button symbol is you have the opportunity to create two additionalstates for it One is for when the user first rolls over the button and anotherfor when he clicks on the button
characteris-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.
Trang 7Make a Simple Button
7 You create new keyframes for the Over and Down states To do this,
click the Over frame, and inser t 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 inser t 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
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
NOTEThe Four States
A button state is the way the
button looks at a par ticularmoment in time The Up statecontains the appearance ofthe button in its normal state
The Over state contains thelook for when the user hovershis cursor over the button
Down is the state when theuser clicks Hit is a specialstate in which you define whatpor tion of the button you in-tend to be clickable The usernever sees the graphic you putinto the Hit state, but theshape of that graphic is whatthe user must “hit” to triggerthe button
Trang 8set 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 asolid 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 asmall button, but you don’t want to frustrate the user by requiring her tohave the precision of a surgeon It’s usually a good idea to make the Hitstate big enough to easily click even if that means that it’s bigger than thebutton
In the task, “Make a Simple Portfolio Viewer,” at the end of this hour, youmake a button with nothing in the Up, Over, or Down states You draw ashape in only the Hit state This creates an invisible button, which meansyou 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 shapemakes the button clickable While you’re working in Flash, invisible but-tons show up as a semitransparent cyan tint, so you can resize and positionthem as needed The advantage of an invisible button is you can use it ontop of any other graphic For example, you might have a large photo onwhich 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’dhave to cut up the image and make a new button for each slice Figure 16.9shows 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.
Trang 9Another 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 ComCom-ponents 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 ButtonsYou can put nearly anything into
a button The only exception isanother button Buttons nestedinside of each other fail to re-spond to any ActionScript
Add Buttons to an imation to Stop and Continue Playback
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
Par t 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
Trang 10TRY IT YOURSELF
▼
Add Buttons to an
An-imation to Stop and
Continue Playback
2 Inser t a new layer for the buttons You don’t want to place buttons inthe layer that has the animation; that would affect the tween Namethe new layer Buttons
3 Into the new Buttons layer, draw a rectangle that becomes a button
Select it, and then conver t it to a symbol by pressing F8 Name itMyButton, and make sure the behavior is set to Button
4 You’re going to need two buttons, so either copy and paste the stance that is already on the Stage or drag another instance of the My-Button symbol from the Librar y onto the Stage in the Buttons layer
in-Apply a Tint color style to each instance—one red for Stop and onegreen for Play As you recall, you do so by selecting the button in-stance on the Stage, using the Properties panel to select Tint fromthe Color drop-down list, and then selecting a color and percentage
5 Give each button a memorable instance name: stopButtonfor redandstartButtonfor green Like adding a label, you use the Propertiespanel 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 Proper tiespanel The instance names are necessar y, so you can specify whatshould happen when the user clicks a button
6 Now you’re going to write the code in a keyframe The code tellsFlash,, “When users click stop, Flash stops, and when they click star t,Flash plays.” Select the first keyframe in the Buttons layer, and openthe Actions panel Write the following code:
stopButton.addEventListener ( MouseEvent.CLICK, myStopHandler ) function myStopHandler( evt ){
stop() }
Translating this code: The first line says the stopButtoninstanceshould broadcast the CLICKevent to the homemade function called
myStopHandler That is, any time the user clicks the stopButtonstance, it triggers the code inside the myStopHandlerfunction Ahomemade function always begins with the word function, followed bythe name of your function; in this case, myStopHandleris followed by
in-an opening in-and closing parenthesis, which is followed by in-an openingand closing curly brace ({}) Exactly what you put between the two curlybraces is up to you You can put one line of code or 1,000 lines ofcode In this case, we put the Timeline action called stop()
7 See whether it works so far Select Control, Test Movie Click theStop button, and the animation should stop Close the .swfyou’retesting to add a listener for the CLICKevent on the Star t button
Trang 11The 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 CLICKevent
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 imation to Stop and Continue Playback
8 Go back to the first frame in the Buttons layer to add more code
Fol-lowing the code that you have, add the folFol-lowing 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 star t button to the myStartHandlerfunction that, in
turn, triggers the play()action
10 Test the movie, and you find when you click the buttons, the movie
plays and stops
Trang 12this way: The button triggers all kinds of events, like the mouse rollingover, 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 executewhen 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 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
ob-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 functionname, shown as myHandler, but don’t start with a number, and don’t usespaces 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 ormouseDown, among other values Recall in the last exercise you used theseemingly 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 bothwork the same way You can probably guess that if you used clickTime, itwouldn’t work, but it would fail silently, meaning you could spend a longtime trying to hunt down the problem However, if you tried
MouseEvent.CLICK_TIME, Flash would immediately squawk at you whenyou 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 literalstring where you type it out between quote marks is risky because younever get a compile-time error if you spell something wrong However, byusing a constant, you never get far without a warning As soon as you typethe period after MouseEvent, you see a code completion drop-down fromwhich you can simply select the event name you had in mind, as shown inFigure 16.10
Trang 13Properties 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()orplay() Another difference is in
the way you used the addEventListener()method You didn’t say
“addEventListener(),” you said “someObject.addEventListener()” with
someObjectbeing the actual button instance name The point is that
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
withgotoAndPlay()and then made the entire animation stop()orplay(),
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
formsomeInstance.stop() If the instance name of your Movie Clip is box,
usebox.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()orplay() However, if you have an instance of a
video, different methods might be available In fact, videos use a method
calledseek(), 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.
Trang 14There’s another powerful way to make the objects onstage change in Flash,and it’s actually simpler than triggering methods Remember, methods areprocesses or things that objects can do Properties are a similar, but simplerconcept Properties are attributes that each Movie Clip instance can have ormaintain independently For example, two Movie Clips could have a differ-ent value for their widthproperty Even two instances of the same MovieClip symbol can have different widths The widthproperty is one of manyproperties Other properties of Movie Clip instances include x(horizontalposition),y(vertical position), and rotation The great news is you alwaysuse the same syntax to access properties:
someInstance.someProperty
For example, you could say myMovieClip.x If you step back and thinkabout the meaning of myMovieClip.x, it doesn’t really mean much If youintend to change the value of a property, you use this form:
totalTimeproperty, 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: ber, if you want to only get the value of a property you still go back to theformsomeInstance.someProperty For example, if you have two instancesonstage named box1andbox2, you can align them both by using
It’d be cool if you could
memo-rize ever y last method and
prop-er ty in ActionScript, but that’s
not practical Instead, it’s best if
you step back and think about
the task you’re tr ying 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, star t by
thinking of what you want to
achieve Compare this to how
you might mail a letter when
traveling in a foreign countr y
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 tr ying to change the volume
for a video You might not know
whether the proper ty 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
Trang 15Make a Simple folio Viewer
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 conver t 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 inser t frames This layer is
the background Name this layer Background
5 Inser t 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 impor ted 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.