Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống
1
/ 40 trang
THÔNG TIN TÀI LIỆU
Thông tin cơ bản
Định dạng
Số trang
40
Dung lượng
11,33 MB
Nội dung
ptg ACTIONSCRIPT 3.0 FOR ADOBE FLASH PROFESSIONAL CS5 CLASSROOM IN A BOOK 33 After the event name, and separated by a comma, is the name of the function that occurs when the ROLL_OVER event takes place. A function is just a block of code that performs one or more, usually related, tasks. An event-handler function is one that responds to an event. Functions can be created and given any name that you like, following the same three rules that we saw for naming variables in Lesson 1, “Using Code Snippets and Navigating the Flash Timeline.” In the example, the function name is showMenu. It is a good idea to name functions so that they describe what they are supposed to do. Reviewing the naming rules in ActionScript Remember that when you are naming variables, functions, classes, and instances in ActionScript, you should follow these three rules: t Use only letters, numbers, and underscores in your names; avoid other special characters. t Do not begin a name with a number. t Avoid spaces in your names; use underscores rather than spaces. e basic syntax for our function looks like this: function showMenu(e:MouseEvent):void { //all the ActionScript to show the menu would go here between the //left and right curly braces. } When creating a function in ActionScript 3.0, always start with the lowercase word function and then the name you choose to give your function. After that, you add a set of parentheses that contains what are called parameters. You will work with parameters more in the coming lessons; for now, it is enough to know that the required parameter for an event-handling function contains a reference to the event that triggered the function. After the parentheses, a colon precedes information about the type of data that the function returns. In this case, void means that the function does not return data. You will learn much more about functions in coming less ons . After that, a pair of curly braces contains all the code that will take place each time an event triggers the function. If all this is not absolutely clear, don’t worry. After a little practice, it begins to make more and more sense, and pretty soon the process will be second nature. And the payoff will be worth it. As already mentioned, becoming comfortable working with Note: # ActionScript is always case sensitive. You may not ice i n t he function and variable names in this book and other places the odd convention of starting with a lowercase character and then beginning subsequent words in the name with uppercase characters, as in showMenu(). While this convention is by no means required, it is a common programming practice, sometimes referred to as “camel case,” that helps indicate what type of item is being dealt with. You may want to consider adopting this convention in your work. ptg 34 LESSON 2 Working with Events and Functions event listeners and event-handling functions is probably the biggest step in learn- ing ActionScript 3.0, and the technique is consistent through the entire language. So what you learn in this lesson will be your entryway into many of the interactive possibilities with ActionScript 3.0. As you saw in Lesson 1, code snippets can be used to create functions that respond to mouse events. You will begin this lesson by using a code snippet that creates an eventListener function that navigates the Flash Timeline when a button is clicked. After this, you will gradually make the transition to writing eventListener code yourself. In your own work, you may prefer to continue to use code snippets as a starting point, or you may find that you can eventually work more efficiently by typing your code yourself. Using code snippets to create navigation is lesson will start with the file from Lesson 1. You can start this exercise with your completed version of that file; otherwise, in Flash CS5, open the lesson02_start.fla file in the Lessons > Lesson02 > Start folder. ptg ACTIONSCRIPT 3.0 FOR ADOBE FLASH PROFESSIONAL CS5 CLASSROOM IN A BOOK 35 Creating button instances to control navigation For many simple Flash web projects, most interactivity consists of navigation trig- gered by button clicks. e ability to write ActionScript that responds to a but- ton CLICK event is also the foundation for understanding much of the rest of the ActionScript language, since all other ActionScript events work in similar ways. To g et yo u star ted with this imp ort ant fu nct ionali ty, F la sh CS5 sh ip s w ith a col- lection of code snippets that write code to create timeline navigation triggered by button clicks. You will soon use one of these snippets, after we add a new button to the project. 1 In the Flash Timeline, select Frame 1 of the buttons layer. 2 If it is not already visible, open the Library panel (Window > Library). 3 From the Library panel, drag an instance of the Button component and place it next to the existing Flash Support button at the lower-right corner of the Stage. 4 Select the new button onstage, and in the Component Parameters section of Property inspector (Window > Properties), locate the label property. 5 In the field to the right of the label property, type Home and press Enter (Windows) or Return (Mac). You should se e the lab el on the button up date to “Home.” You w ill use this button to allow the user to navigate to the home frame. Now give the button an instance name. 6 With the Home button selected, go to the Property inspector, place the cursor in the instance name field, and give the button the instance name home_btn. Note: # Instance names follow the naming rules already discussed for variables and functions. ptg 36 LESSON 2 Working with Events and Functions The importance of instance names It is essential to give an instance name to all onstage buttons, movie clips, and other objects that you wish to control with ActionScript. One of the most common mistakes made by new ActionScript programmers is writing their code correctly but forgetting to give their objects instance names. Checking your instance names is often a good place to start when troubleshooting code that is not working. Adding a code snippet for navigation e intended purpose of the Home button you just added is to allow the user to jump to the frame of the Timeline labeled home when the button is clicked. You can use the Code Snippets panel to add some code to make this work. 1 If they are not already visible, open the Actions panel (Window > Actions) and the Code Snippets panel (Window > Code Snippets). 2 In the Timeline, select Frame 2 of the Actions panel. is is the frame where you will place the code snippet. About code in the Timeline In the first two lessons, you are placing code in multiple frames of the Flash Timeline. This is a common technique in simple Flash websites. However, for more complex projects, many ActionScript developers often avoid putting ActionScript in multiple frames but instead try to write all of their ActionScript in a single frame or use external ActionScript files with no timeline code at all. As you get comfortable enough with ActionScript to make these choices, you can determine what works best for you and for each individual project. You will learn how to work with external ActionScript files in Lesson 4, “Creating ActionScript in External Files,” and you will create an interactive project that loads content into a single frame in Lesson 5, “Using ActionScript and Components to Load Content.” 3 On the Stage, select the button with the label Home. Remember that this button has been given the instance name home_btn. 4 In the Code Snippets panel, open the Timeline Navigation folder and double- click the snippet named Click To Go To Frame And Stop. ptg ACTIONSCRIPT 3.0 FOR ADOBE FLASH PROFESSIONAL CS5 CLASSROOM IN A BOOK 37 You should now see the following code in the Ac tions panel b elow the co de that was already there: /* Click to Go to Frame and Stop Clicking on the specified symbol instance moves the playhead ¬ to the specified frame in the timeline and stops the movie. Can be used on the main timeline or on movie clip timelines. Instructions: 1. Replace the number 5 in the code below with the frame ¬ number you would like the playhead to move to when the symbol ¬ instance is clicked. */ home_btn.addEventListener(MouseEvent.CLICK, fl_ClickToGoToAndStopAtFrame); function fl_ClickToGoToAndStopAtFrame(event:MouseEvent):void { gotoAndStop(5); } e code snippet that was created added an event listener for the Home button instance. Now, when the button is clicked it will automatically call the function that is somewhat verbosely named fl_ClickToGoToAndStopAtFrame (changing the function name in a code snippet does not modify its behavior, and you will change this function’s name in the next section). When a function is called, all the code between the curly braces is executed. In this case, that means that when the user clicks the Home button, the function will send the Timeline to Frame 5. e goto action is the same as we used in Lesson 1. e only difference is that now it is triggered by a button event. You will modify the frame that this function navigates to in the next section. ptg 38 LESSON 2 Working with Events and Functions Modifying the code snippet Code snippets provide a very easy way to create correct ActionScript syntax, but rarely does any given code snippet perform exactly the function that you want. More typically, you choose that snippet that most closely matches your needs and then customize the code to suit your purpose. You will make a few modifications to the code snippet you just created to make it perform the way you want and make it easier to read. Remember that the light gray characters in the code snippet are descriptive and nonfunctional comments. If you read the Instruction comments, you will see that to make this code navigate to a desired frame, you replace the number 5 in the line that reads gotoAndStop(5); with a reference to the frame that you actually want the user to go to. One way to do this is to simply replace the 5 with a different number. In the case of the home frame, this would be Frame 50. However, a better way to refer to this frame in the code would be by its label name. Using label names instead of frame numbers in your scripts makes it much easier to make changes to the content in the frames of your Timeline without having to modify your code. You use frame labels in a goto method by typing the label name in quotation marks between the parentheses that now contain the number 5. 1 In the Actions panel, modify the line that reads: gotoAndStop(5); so that it now reads: gotoAndStop("home"); 2 Save your work and test your movie (Control > Test Movie). If you click the Home button while the opening animation is playing, the Timeline should skip directly to the home frame. 3 Close the lesson02_start.swf file to leave the testing environment. You can see how eas y it is to modif y the co de snippe t to achieve the desired navigation. It would be no problem to leave this code as it is in your project. However, a couple of additional modifications to the code snippet will make it easier to work with as your project develops. One change you may wish to make to the code snippet is renaming the function. Right now the function has the long and generic name fl_ClickToGoToAndStopAtFrame. It is a good practice to name your functions ptg ACTIONSCRIPT 3.0 FOR ADOBE FLASH PROFESSIONAL CS5 CLASSROOM IN A BOOK 39 in a way that describes their specific purpose. Let’s change the snippet’s default function name to the shorter and more descriptive name goHome. You will need to change this name in two places: in the addEventListener method and in the function itself. 4 In the Actions panel, locate the line that reads: home_btn.addEventListener(MouseEvent.CLICK, ¬ fl_ClickToGoToAndStopAtFrame); 5 Change this line to: home_btn.addEventListener(MouseEvent.CLICK, goHome); 6 Next locate the line that reads: function fl_ClickToGoToAndStopAtFrame(event:MouseEvent): ¬ void { 7 Change this line to: function goHome(event:MouseEvent):void { Changing the function name in this way has no effect on the code’s behavior, but it does make it more succinct and easier to understand. After you have used a code snippet a few times and understand the included comments (in gray), you may want to delete the comments; doing so does not affect the behavior of the code. 8 Delete the comments. Here is the code so far for Frame 2 with comments removed: info_txt.text = String(count); home_btn.addEventListener(MouseEvent.CLICK, goHome); function goHome(e:MouseEvent):void { gotoAndStop("home"); } As you get more comfortable with ActionScript, you will probably want to make a few additional modifications to this code to make it still easier to read, but for now let’s move on. Having successfully created button navigation with a code snippet, you will now try creating similar code by typing it yourself. ptg 40 LESSON 2 Working with Events and Functions Creating event listeners Although code snippets are convenient, to get the most out of ActionScript 3.0 it is important to be thoroughly confident in your understanding of basic ActionScript syntax. is competence comes only with time, study, and practice. Once you have mastered the syntax for an ActionScript task, you may still find that code snip- pets are often a great time-saving tool. Now, though, it’s time to begin writing ActionScript code on your own. You’ll start by creating another event listener, writing your own code from scratch. Adding a restart button Now let’s add some functionality on the home page to enable the user to restart the animation. 1 Add a keyframe (F6) to the buttons layer on the home frame. 2 Click somewhere on the Stage away from the two buttons to deselect them, and then select just the Home button. 3 With the Home button selected, go to the Property inspector (Window > Properties) and change the label name from Home to Restart. 4 Also in the Property inspector, with the button still selected, change the button’s instance name from home_btn to restart_btn. 5 With the Actions panel visible, select the home frame of the actions layer. 6 Add the following code in the Actions panel below the existing code: restart_btn.addEventListener(MouseEvent.CLICK, goStart); Be careful to match the capitalization exactly, and notice that addEventListener and MouseEvent.CLICK turn blue when typed correctly. e color-coding of ActionScript as you type provides useful feedback to let you know you are typing things correctly. Keywords in ActionScript 3.0 turn blue by default. If you type something that is part of the ActionScript language and it appears as black text, double-check your spelling and capitalization. After this code has been added, when the Restart button is clicked it will try to call a function named goStart. So, let’s add this function to make the code work. 7 In the Actions panel, on a line below the code you just added, insert the following code: function goStart(e:MouseEvent):void { count=1; gotoAndPlay("loop"); } Note: # It doesn’t matter how many empty lines you place between sections of your code. Many programmers like to leave space between sections of code for clarity; others like to keep things concise by starting new blocks of code on every line. As you start to get comfortable with ActionScript, you will find a style that you prefer. ptg ACTIONSCRIPT 3.0 FOR ADOBE FLASH PROFESSIONAL CS5 CLASSROOM IN A BOOK 41 is function will be the one that responds to a click of the Restart button. When the function is called, the Timeline will be sent back to the beginning of the animation, and the variable count will be reset to 1. Remember that count is the variable that keeps track of the number of times that the opening animation has played, so by setting count to 1, you are restarting the movie with its initial setting. 8 Save your work and test your movie. When you reach the home frame in the testing environment, the button that previously said “Home” should now say “Restart.” e Restart button should respond to the code you added by replaying the opening animation, with the button again reading “Home.” Notice that the Flash Support button works the same throughout. Because you did not change its instance name, it always responds to the listener and function that you created for it on Frame 1. If everything is working, congratulations! You are well on your way to being com- fortable with ActionScript 3.0. If you had problems with your code, compare it carefully with the example code. If there are errors in the code, the Output panel should appear with descriptions of the errors, and it will show on which lines they appear. Note which line numbers contain the errors, and check your spelling and the color-coding of your ActionScript on those lines. Especially make note of capi- talization, and be sure that the instance names of your buttons match the names in your event listeners. Modifying the text field dynamically Right now, when your movie loops over the opening animation, the text field is instructed to display the number representing the number of times the animation has played. e number is currently accurate, but the user feedback is not elegant. ptg 42 LESSON 2 Working with Events and Functions Let’s make the information in the text field more useful by adding some prose to the field to make a complete sentence. 1 With the Actions panel and the Timeline visible, select the loop frame (Frame 2) in the actions layer of the Timeline. 2 In the Actions panel, change the code that currently reads: info_txt.text = String(count); so that it reads: info_txt.text = "The animation has played " + String(count) + ¬ "x."; e plus signs are used to concatenate (or join) the literal text (in quotation marks) with the value of the count variable to form a sentence. 3 Save your work and test the movie once more. e text field should now read “e animation has played 1x (2x, 3x, and so on).” Adding buttons to control language To s oli di f y what yo u’ve covered s o far, a dd a few mo re b utton s to the Sta ge to let the user control the language that is displayed in the text field. You will begin by adding a variable that keeps track of the user’s language choice and sets a default language to the first frame of the movie. 1 With the Actions panel and the Timeline visible, select Frame 1 of the actions layer. 2 Add the following code below the existing code: var language:String = "English"; Now you’ll add code that checks the value of the language variable before adding text to the text field. [...]... the case when comparing a task in ActionScript to a similar task performed in the Flash interface, the main benefit of creating tweens in code rather than on the Timeline is that the resulting animation can be more versatile and more interactive Using code also means that tweens can be created on a single frame of the Timeline, or even without any frames at all ACTIONSCRIPT 3.0 FOR ADOBE FLASH PROFESSIONAL. .. easing that you want Easing classes in ActionScript 3.0 Easing is a technique for accelerating or decelerating the velocity of the start or end of an animation In Flash CS5, easing can be controlled in the interface or with ActionScript ActionScript provides quite a few built -in easing classes that create a wide variety of easing effects, including a CustomEase class that lets you create your own easing... includes many animation capabilities, including 3D animation, built -in inverse kinematics with springing, and a robust Motion Editor When you are creating a cartoon or some other type of linear animation, the Flash Timeline and interface offer great and easy-to-use animation features However, by learning to control animation with ActionScript, you can create animation that is very interactive and responsive... ACTIONSCRIPT 3.0 FOR ADOBE FLASH PROFESSIONAL CS5 CLASSROOM IN A BOOK 51 Note: Transparency and most values that are measured in percentages usually range from 0 to 1 in ActionScript 3.0, rather than from 0 to 100 The scaleX and scaleY properties are designated similarly: A scale value of 1 means that the object is set to 100 percent of its original size; a scale value of 2 means that it’s set to 20 0 percent,... click various buttons to see the results of changing the instrument properties Creating animation using ActionScript tweens Just as you can create animation using tweens on the Timeline, you can create tweens in ActionScript (for a review of creating tweens in the Timeline or an overview of the tweening features in Flash CS5, see the Flash Help files or Adobe Flash Classroom in a Book by Adobe Press) As... to a movie clip Notice that after you typed the last line of code, Flash may have automatically added this line to your Actions panel: import flash. display.MovieClip; This automatic insertion of import statements is a new feature added in Flash CS5 Any time you create a variable of a certain data type for the first time, Flash imports the class that describes that data type (you will learn more about... comparing values, because a single equals sign (=) is what is used to set one value to equal another In other words, a single equals sign in this example would be used to set language to English, not to check to see if language is English ACTIONSCRIPT 3.0 FOR ADOBE FLASH PROFESSIONAL CS5 CLASSROOM IN A BOOK 43 Note: In a Flash project that has large amounts of content for different languages, the translations... existing code in Frame 1 of the actions layer, add a new variable called instrument: var instrument:MovieClip = banjo; When creating a variable, you set the data type by typing a colon after the variable’s name and then indicating the type of data that will be stored in this variable Notice that the data type of this variable is set to MovieClip This means that the value of instrument will always be a. .. seconds var spin:Tween = new Tween(instrument, "rotation", ¬ Elastic.easeOut, 0, 360, 5, true); ACTIONSCRIPT 3.0 FOR ADOBE FLASH PROFESSIONAL CS5 CLASSROOM IN A BOOK 65 4 CREATING ACTIONSCRIPT IN EXTERNAL FILES Lesson overview In this lesson, you will learn to do the following: Create an ActionScript file using the tools in Flash CS5 Create an ActionScript class that extends the MovieClip class Create a constructor... For more information, see the Flash CS5 ActionScript 3.0 language reference in the Flash Help files A reference to a new tween instance in ActionScript is typically stored in a variable The syntax is similar to that for other variables you have created: var tweenName:Tween = new Tween(objectToBeTweened, ¬ "propertyToBeAnimated", EasingType, startingValue, ¬ endingValue, time, trueForSeconds); When a . that file; otherwise, in Flash CS5, open the lesson 02_ start. a file in the Lessons > Lesson 02 > Start folder. ptg ACTIONSCRIPT 3. 0 FOR ADOBE FLASH PROFESSIONAL CS5 CLASSROOM IN A BOOK 35 Creating. the value of the language variable before adding text to the text field. ptg ACTIONSCRIPT 3. 0 FOR ADOBE FLASH PROFESSIONAL CS5 CLASSROOM IN A BOOK 43 3 With the Actions panel and the Timeline. ptg ACTIONSCRIPT 3. 0 FOR ADOBE FLASH PROFESSIONAL CS5 CLASSROOM IN A BOOK 33 After the event name, and separated by a comma, is the name of the function that occurs when the ROLL_OVER event takes