Flash CS4 Professional in 24 Hours- P11

Chia sẻ: Cong Thanh | Ngày: | Loại File: PDF | Số trang:30

lượt xem

Flash CS4 Professional in 24 Hours- P11

Mô tả tài liệu
  Download Vui lòng tải xuống để xem tài liệu đầy đủ

Flash CS4 Professional in 24 Hours- P11: The creation of this book could not have happened without the skill and patience of many, many people at Sams Publishing. Most of all, I want to thank Mark Taber for offering me this opportunity and Philip Kerman for writing such a great book. I also greatly appreciate the efforts of Songlin Qiu for keeping me on track and organized, not an easy task.

Chủ đề:

Nội dung Text: Flash CS4 Professional in 24 Hours- P11

  1. 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. In this task, you make the last few frames of an animation loop. Follow TRY IT YOURSELF ▼ these steps: Make an Action That 1. In a new file, use the Text tool to create a text block containing the Loops Part of Your word Welcome. Make sure the text type is Static. Select the block and Movie 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).
  2. 292 HOUR 16: Basic Interactivity ▼ TRY IT YOURSELF Make sure Frame 30 remains selected when you edit the Actions Make an Action That panel by noting the tab near the bottom of the panel reads Actions:30 Loops Part of Your and has the keyframe icon, as shown in Figure 16.2. This confirms the Movie script you’re about to write executes when the playback head reaches Frame 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. 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. FIGURE 16.3 After you insert gotoAndPlay, the Actions panel is populated.
  3. Basic ActionScript 293 6. You always type any required parameters inside the parentheses. In TRY IT YOURSELF ▼ this case, type the number 20 because that’s the frame number to Make an Action That which you want to go and play. Therefore, the finished action in the Loops Part of Your script area should read gotoAndPlay(20). Movie 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. 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. In this task, you improve the gotoAndPlay action by supplying a frame la- TRY IT YOURSELF ▼ bel instead of a frame number. Follow these steps: Use a Frame Label as 1. In the file created in the preceding task, click Frame 20 of the Anima- the Destination of a tion layer, and insert a keyframe. In the Properties panel under Label, gotoAndPlay Action 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.
  4. 294 HOUR 16: Basic Interactivity ▼ TRY IT YOURSELF Use a Frame Label as the Destination of a gotoAndPlay Action 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. 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. 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?
  5. 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
  6. 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. ▼ TRY IT YOURSELF In this task, you make a simple but useful button. Follow these steps: Make a 1. In a new file, draw an oval or a rectangle that becomes your button. Simple 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. FIGURE 16.6 Any shape can be used as a 6. Close the .swf you’re testing, so you can edit the button. Double-click button. The user’s cursor changes to a hand when it’s the instance on the Stage, and you are taken inside the MyButton over the button. 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.
  7. Making Simple Buttons 297 TRY IT YOURSELF ▼ Make a Simple Button FIGURE 16.7 Four frames for the four states of a button are inside a button. 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. 7. You create new keyframes for the Over and Down states. To do this, The Over state contains the click the Over frame, and insert a keyframe. Select the Free Trans- look for when the user hovers form tool, and then scale the contents of the second frame (the Up his cursor over the button. state) by making it a tad larger. Down is the state when the 8. Select the third frame (the Down state), and insert another keyframe. user clicks. Hit is a special Select the button’s shape in the new keyframe (Frame 2), and nudge it state in which you define what two pixels down and two pixels to the right. portion of the button you in- tend to be clickable. The user 9. Test the movie. This time the button should grow when you roll over it; never sees the graphic you put click, and move down and to the right when you click it. into the Hit state, but the shape of that graphic is what the user must “hit” to trigger the 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
  8. 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 FIGURE 16.8 have the precision of a surgeon. It’s usually a good idea to make the Hit Changing the shape contents of a button’s Hit state affects what por- state big enough to easily click even if that means that it’s bigger than the tion is clickable. 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.9 Invisible buttons enable you to make any area clickable rather than make a new button for each spot.
  9. Listening for Events 299 Another important note about buttons: You can put anything you want into NOTE those three keyframes (Up, Over, Down). You get only one keyframe for No Buttons in Buttons each, but that doesn’t mean you can’t put more than one Movie Clip sym- You can put nearly anything into bol in that frame. If you create a Movie Clip that contains a 10-frame anima- a button. The only exception is tion and then place that Movie Clip in the Over state for a button, the user another button. Buttons nested sees that animation play and continue to loop when her mouse is over the inside of each other fail to re- button. In this way, you can make animated buttons. spond to any ActionScript. 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. In this task, you add buttons that enable the user to stop and continue the TRY IT YOURSELF ▼ animation from the task earlier this hour. Follow these steps: Add Buttons to an An- 1. Either use the file created in the task, “Make an Action That Loops imation to Stop and Part of Your Movie,” or make a new Flash File (ActionScript 3.0) with a Continue Playback 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.
  10. 300 HOUR 16: Basic Interactivity ▼ TRY IT YOURSELF 2. Insert a new layer for the buttons. You don’t want to place buttons in Add Buttons to an An- the layer that has the animation; that would affect the tween. Name imation to Stop and the new layer Buttons. Continue Playback 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.
  11. Listening for Events 301 8. Go back to the first frame in the Buttons layer to add more code. Fol- TRY IT YOURSELF ▼ lowing the code that you have, add the following code: Add Buttons to an An- startButton.addEventListener ( MouseEvent.CLICK, myStartHandler ) imation to Stop and function myStartHandler( evt ){ Continue Playback 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. 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
  12. 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.
  13. Listening for Events 303 FIGURE 16.10 The code completion drop-down helps you select the appropriate event name. 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().
  14. 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 TIP Clip symbol can have different widths. The width property is one of many Learning Without properties. Other properties of Movie Clip instances include x (horizontal Memorizing position), y (vertical position), and rotation. The great news is you always It’d be cool if you could memo- use the same syntax to access properties: rize every last method and prop- someInstance.someProperty erty in ActionScript, but that’s not practical. Instead, it’s best if you step back and think about For example, you could say myMovieClip.x. If you step back and think the task you’re trying to achieve, about the meaning of myMovieClip.x, it doesn’t really mean much. If you and write it out using your own intend to change the value of a property, you use this form: words. This is called someInstance.someProperty = someValue pseudocode. If you can write out the instructions for the task at hand using your own words, then For example, to move a Movie Clip instance named myMovieClip, 100 pix- the process of translating to ac- els from the left edge of the stage, you’d say tual ActionScript becomes me- myMovieClip.x = 100 chanical. It’s not easy to “think in ActionScript.” So, start by In this example you’re setting the x property to 100. You can read the equals thinking of what you want to achieve. Compare this to how sign as “is now equal to,” or in English, “myMovieClip’s x is now equal to 100.” you might mail a letter when Like methods, the available properties vary based on object types. Buttons, traveling in a foreign country. Movie Clips, and Videos all have a property for x, but only Videos have a You might not know the word for totalTime property, which contains the total number of seconds in the video. “post office,” but you can proba- bly assume they have such a One last point before you get to try all this out on some real tasks: Remem- place; it’s just a matter of find- ber, if you want to only get the value of a property you still go back to the ing the correct word. This is sim- form someInstance.someProperty. For example, if you have two instances ilar to working in ActionScript onstage named box1 and box2, you can align them both by using and trying to change the volume for a video. You might not know box1.x = box2.x whether the property is called soundLevel, volume, or Notice it’s box1 that is moving so its x property is equal to box2’s. The fol- loudness, but you can probably lowing exercise should help solidify your understanding of ActionScript. 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 ActionScript Application with actual ActionScript as you The task that remains this hour gives you a chance to practice what you’ve hunt down the language syntax. learned so far, but it’s also a practical task.
  15. Listening for Events 305 In this task, you make a tool that enables you to view different images. TRY IT YOURSELF ▼ Most of the work in this task revolves around structuring the file and not Make a Simple Port- so much writing ActionScript. folio Viewer 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.
  16. 306 HOUR 16: Basic Interactivity ▼ TRY IT YOURSELF 7. You’re finished with the Content Movie Clip, so return to the main Make a Simple Timeline by clicking Scene 1. Portfolio Viewer 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
  17. Listening for Events 307 TRY IT YOURSELF ▼ Make a Simple Port- folio Viewer 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. 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.
  18. 308 HOUR 16: Basic Interactivity ▼ TRY IT YOURSELF 17. The structure was the hard part. The ActionScript part looks simple in Make a Simple comparison. Select the first keyframe in your file, and enter the follow- Portfolio Viewer 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); } 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!
  19. Summary 309 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.
  20. 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.
Đồng bộ tài khoản