Successfully reported this slideshow.

Basic Actionscript - Supplementary Notes


Published on

Published in: Education
  • Be the first to comment

  • Be the first to like this

Basic Actionscript - Supplementary Notes

  1. 1. Basic Actionscript  Supplementary Notes [Basic Actionscript]   Page 1 
  2. 2. Basic Actionscript  Programming & Scripting Programming & Scripting is a method for a computer to understand what human wants the system to do. Programming is more into a full stand alone program, but scripting is embedded or depending onto other program (Eg. Actionscript depends on Flash, Javascript depends on HTML, etc) Action Script is the scripting language used in Adobe Flash Use Action Script when: - Interaction between Flash and user is needed - There is a need to control the flow of animation, sound or video - External data need to be loaded into Flash - There are a lot more as Flash is evolving from time to time Markup Language is a language to describe how the content of information is structured and formatted Some examples of Markup Languages are HTML, XML, XHTML etc   Page 2 
  3. 3. Basic Actionscript  1. Introduction to programming Concept How complex or simple a program or script, they actually are collection of statements (individual command) that are composed in such way, to generate a task (or set of tasks) For example, we want to make a program called “Making Instant Coffee”, there might be a set of statements such 1. Prepare a glass / cup 2. Prepare coffee, sugar & milk 3. Put 2 spoons of coffee 4. Put 1 spoon of sugar 5. Pour hot water 6. Pour Milk 7. Stir the coffee As we can see the above statement, there is a sequence / flow from statement 1 to statement 7. Of course, the flow of statement 3 to 6 is not absolute, as human can make coffee but putting sugar, milk or coffee first, but the main point here is a computer knows how to execute the command line by line / in a sequence. Flowchart Flowchart is a method to visualize a process especially in the programming field. Resources: - - - - - Please refer to flowchart symbol provided as appendix (from IBM & Wikipedia) [Logic Concept & Flowchart Exercise] Create a Logic Concept & Flowchart at least 2 from 3 options below 1. Purchase 2 hourly Met Card for Zone 1 the Cashier Counter at Flinders Station 2. Communicate via Mobile phone (From dialing until hanging up) 3. Borrow book from State Library – Melbourne   Page 3 
  4. 4. Basic Actionscript  2. Introduction to Actionscript Some important concepts (taken from apart from knowing that computer execute the command line by line are: - Variable & Data Type - Operator - Condition - Loop - Function (Will be covered in the future lesson) - Property, Method & Event Resources: - - Variable It can be assumed as container. A container where we can put an object at one time or collection of same objects at one time. We may say a container of orange (Container that is filled with orange) or a container of chicken. Sample Code: //Define a variable and assign value inside it box1 = orange; //A better way to define a variable and //assign value inside it var box2 = apple; //Define 2 different variables & assign value separately var box3, box4; box3 = banana; box4 = pineapple; There are some rules for naming a variable: - Variable cannot have a space and any special character (. / * etc) except $ o var box 1 = guava; - Variable cannot use Flash / Actionscript reserved word o var catch = monkeys; - Variable cannot start with number o var 3boxes = rhino; - Variable must be descriptive and consistent o var getUserName = John; o var getUserEmail =;   Page 4 
  5. 5. Basic Actionscript  3. Data Type Defining variable without define the data type, the type of data used for particular variable will not complete a good practice of action scripting, even though Flash (Action script 1.0 & 2.0) is a little bit lenient in regard to use data type variable Sample Code: //Define a variable and assign string value inside it box1 = “orange”; //A better way to define a variable with string data type & //assign value inside it var box2:string = “apple”; Some commonly used data types: - Number includes positive & negative integer (Whole number) or decimal (Floating point) o var myPositiveNumber:Number = 2; o var myNegativeNumber:Number = -5; o var myDecimalNumber = 3.5; - String includes 1 single character, word or even a sentence and must be delimited by double quote (“) o var singleCharacter:String = “a” o var singleWord:String = “Word” o var singleSentence:String = “Hello World from SGI”; - Boolean data type that can contain on tru or false value o var trueValue:Boolean = true; o var falseValue:Boolean = false; [Data type Exercise] Please indicate which Data type is used for each variable below 1. “Hello World” 2. True 3. 23.789 4. -20 5. “No regret” 6. “Actionscript 3.0” 7. “False” 8. 0 9. “123 + 456” 10. False   Page 5 
  6. 6. Basic Actionscript  4. Output & Dynamic Text in Flash Flash provides the author with trace() function to display any sentences & variable content inside ( ) (Bracket after trace function) into output window. Any value that is displayed on the Output Window will not be visible to user when swf file is published. Another method for Flash to actually display the value from actionscript is using Dynamic Text by assigning either as variable or as dynamic text Name [Data Type Output Exercise] Please indicate which Data type is used for each variable below by using Dynamic Text in Flash 1. “Hello World” 2. True 3. 23.789 4. -20 5. “No regret” 6. “Actionscript 3.0” 7. “False” 8. 0 9. “123 + 456” 10. False 5. Input & Input Text in Flash Author can set the value into variable (as we call it input) or by using Input Text to retrieve the value by user when the swf file is run. Similar to Dynamic Text, Input Text can be used by assigning as variable or input text name [Greeting Exercise] Create a program to retrieve the input by user (name) and display the input text as dynamic text E.g. User is allowed to enter his/her name into input text, then he press Submit Button to display the greeting by using Dynamic Text such as “welcome username”   Page 6 
  7. 7. Basic Actionscript  6. Operator Variable is not only used for storing and retrieving data value. Programmer might need to operate on variable so it gives useful information. It is called operating variable There are some operators that come quite handy for handling variables: o Numeric Operator (+, - , /, &, %)  Assume that variable1 = 10, variable2 = 5  Addition = variable1 + variable2; (Answer is 15)  Subtraction = variable1 – variable2; (answer is 5)  Multiplication = variable1 * variable2; (Answer is 50)  Division = variable1 / variable2; (Answer is 2)  Remainder = variable1 % variable2; (Answer is 0) !!! Special !!!  variable1 = variable1 +1 can be written as  variable1 += 1 or variable1++  variable2 = variable2 - 1 can be written as  variable2 -= 1 or variable2--  variable3 = variable3 * 1 can be written as  variable3 *= 1  variable4 = variable4 +1 can be written as  variable4 /= 1 [Cash Machine Exercise] Create a program to retrieve the amount of the item, the price of each item and the cash submitted. After retrieving the input from user, the program will redisplay the input data from user and the sub total of the item price, the paid cash and the returned cash   Page 7 
  8. 8. Basic Actionscript  7. Array in Flash Array is a type of variable that can hold multiple values. The analogy of array would be like a locker with number. The locker can hold different types of item (at one time) and the number will tell the indexing funciton (position) myLocker = new Array (“Shoes”, “Shirt”, “Ball”); or myLocker = [“Shoes”,”Shirt”,”Ball”]; The Array may contain different type of data myLocker = [1,2,3,”four”,”five”,”six”]; You may also assign the value into specific position of the array myLocker[0] = “Shoes”; myLocker[1] = “Shirt”; myLocker[2] = “Ball”; As you can notice, the array starts with 0 as the first position of the item. To retrieve the value of the array, you can use myCurrentItem = myLocker[1]; /*Shirt will be the retrieved value”s*/ There are some other predefined function for array to - Get the length of the array (Highest Index number + 1) arrayLength = myLocker.length; - Add element at the end of the array myLocker.push(“Cap”,”Sock”); - Remove the last element of the array myLocker.pop(); - Remove the first element of the array myLocker.shift();   Page 8 
  9. 9. Basic Actionscript  8. 2D Array in Flash To create 2D Array, we just need to manipulate the array a little bit myGrid = new Array(new Array(“1-1”,”1-2”),new Array(“2-1”,”2-2”)); or myGrid[0][0] = “1-1”; myGrid[0][1] = “1-2”; mygrid[1][0] = “2-1”; mygrid[1][1] = “2-2”; [Zodiac List Exercise] Create 2D Array to store the Zodiac List, The date range & the prediction for current month and use Dynamic text to display the list of the Zodiac complete with the date range & prediction 9. If ... Then ... Else Conditional Statement Sometimes, there is to use simple decision making program where a certain condition is satisfied For example, if a student has result more than or equal to 50, then the student has passed Sample code: if(studentMark >= 50){ trace(“You have passed”); } There is a need as well to state the else condition to give better explanation to the user Sample code: if(studentMark >= 50){ trace(“You have passed”); }else{ trace(“You have failed”); } There might be multiple conditions to satisfy to get different responses Sample code: if(studentMark >= 50){   Page 9 
  10. 10. Basic Actionscript  trace(“You achieve PASS”); }else if(studentMark >= 65){ trace(“You achieve CREDIT”); }else if(studentMark >= 75){ trace(“You achieve DISTINCTION”); }else if(studentMark >= 85){ trace(“You achieve HIGH DISTINCTION”); }else{ trace(“You have FAILED”); } 10. Switch ... Case If there are definite 1 (one) value for each condition, we can use Sample code: Switch(day){ case “Monday”: { Trace(“Today is Monday”); Break; } case “Tuesday”: { Trace(“Today is Tuesday”); Break; } case “Wednesday”: { Trace(“Today is Wednesday”); Break; } case “Thursday”: { Trace(“Today is Thursday”); Break; } case “Friday”: { Trace(“Today is Friday”); Break; } case “Saturday”: { Trace(“Today is Saturday”); Break; } Default: {   Page 10 
  11. 11. Basic Actionscript  Trace(“Today is Sunday”); } } [Harry Potter Alphabet Exercise] Create a list of vocabularies used in harry Potter movie, and use 2D array to store the Alphabets & Alphabets Description. Input text must be used to retrieve the request from the user and display the according alphabet that is entered by user   Page 11 
  12. 12. Basic Actionscript  11. Symbols in Flash revisited There are 3 symbols that can be used in Flash: - Graphic = This symbol cannot have name and cannot be controlled by actionscript - Movieclip = This symbol can have a name, it has it’s own timeline and can be controlled by actionscript - Button = This symbol can have a name, it is treated as a button (in fact, it is a button), it can be controlled with actionscript. The symbols above (Movieclip & Button) have properties and methods that can be manipulated by actionscript & event to react to Properties are the attributes of the object such as width, height, position, rotation, alpha etc Methods are the function of the object such as play(), stop(), etc Events are the trigger of the object to react to such as on(release), on(press), on(rollOver), etc [Properties, Methods & Events Exercise] 1. List down the Properties, Methods & Events for Movieclip & Button for actionscript 2.0 2. Show example of the properties & methods manipulation by button upon movieclip such as changing the size, changing the position, changing the rotation, changing the opacity of the movieclip 12. Animation in Flash revisited There are at least 5 different animations in Flash 1. Frame by Frame Animation = Animation where the author need to create different appearance, position, etc from one keyframe to another 2. Shape Tweening Animation = Animation of the shape where the author can change the shape of the object uncontrollable or uncontrollable (with Shape hints) 3. Motion Tweening Animation = Animation that requires symbols as the animated object, reusing the symbol will reduce the animation file size 4. Guided Animation = Motion Tweening Animation that uses guide layer to control the movement direction   Page 12 
  13. 13. Basic Actionscript  5. Masked Animation = It can be either Shape Tweenign Animation, Motion Tweening Animation, Guided Animation, Frame by Frame Animation or combination of the above with masking object as the display area [Animations Exercise] Create simple animations for each animation types above (Frame by Frame, Shape Tweening Animation, Motion Tweening Animation, Guided Animation & Masked Animation) --- QU∑ST1ON? ---   Page 13 
  14. 14. Basic Actionscript  13. Controlling Timeline Animation relies heavily on timeline. Fortunately, by using action script, the flash programmer is able to control the timeline right at the root or within movie clip symbol. Controlling ROOT timeline - Controlling by using frame number o gotoAndStop(frame number); o gotoAndPlay(frame number); gotoAndStop tells Flash to go the frame number that has been set within the bracket and stop, gotoAndPlay tells Flash to go to the frame number and play until in hits stop() action or reaching the end of the timeline and go back to the 1st frame - Controlling by using Label o gotoAndStop(“label name”); o gotoAndPlay(“label name”); This option is better compared to go to frame number. If the timeline is extended or shortened, the Flash programmer does not need to modify / revise the code as the timeline controller depends on the label in which they are moved according to the frame addition or subtraction   Page 14 
  15. 15. Basic Actionscript  - Controlling by using scene o gotoAndStop(“scene name”, frame number); o gotoAndStop(“scene name”, frame number); If the programmer wants to separate one scene to another in which it will be easier to modify one separate scene rather than modifying the whole animation in one scene Controlling Movie Clip Flash programmer con control the timeline within movie clip in the same way as controlling the root timeline using frame number or label. Programmer just needs to include the instance name of the movie clip prior to using gotoAndStop() or gotoAndPlay() function E.g. o movieCLipName.gotoAndStop(frameNumber); o movieCLipName.gotoAndPlay(frameNumber); o movieCLipName.gotoAndStop(“labelName”); o movieCLipName.gotoAndPlay(“labelName”);   Page 15 
  16. 16. Basic Actionscript  14. Date Function in Flash Date function can be used to retrieve current information on date and time including date, day, month, year, hour, minute and second. o currentTime = new Date(); o currentDate = currentTime.getDate(); o currentMonth = currentTime.getMonth(); o currentYear = currentTime.getFullYear(); o currentHours = currentTime.getHours(); o currentMinutes = currentTime.getMinutes(); o currentSeconds = currentTime.getSeconds(); The above code is useful to create a Digital Clock in Flash, but to create Analog Clock, programmer needs to determine the angle of hour, minute and second pointer o currentHours = currentHours%12; o hoursHand._rotation = (currentHours/12)*360; o minutesHand._rotation = (currentMinutes/60)*360; o secondsHand._rotation = (currentSeconds/60)*360;   Page 16 
  17. 17. Basic Actionscript  15. Loop It’s used to repeat 1 (one) or more statements until a certain condition is satisfied. There are 3 different loops that we can use in Action Script For Loop = Repetition is executed for definite number of times Sample Code: for(counter=0;counter<10;counter++){ statement1; statement2; } While Loop = Repetition is executed while the condition is satisfied Sample Code while(counter<10){ statement1; counter++; } Do … While Loop = Repetition is executed at least once and the next execution depends on the stated condition Sample Code: Do{ Statement1; Counter++; }while(counter<10);   Page 17 
  18. 18. Basic Actionscript  16. Function Function is reusable chunk of code - Reusable: The code is created once, but it can be called many time to execute the statements inside that function - Chunk: It’s beneficial to create small independent code, rather than 1 big complicated code. It’s easier to maintain and modified as well - Code: Statement even as simple as “trace()” method To create a function, it’s like making a Pandora box, programmer / user who uses the function does not need to know what’s inside the code, as long as he / she knows what the function for, what’s the input (parameter) of the function and what the output is. For example, if there is a function called “Multipy”, the user od the code does not need to know what statement is used to multiply, instead he/she just need to know how many parameters are available with this function. If the function shows “Multiply(a,b)”, it means that 2 parameter will be calculated. User need to know as well what the output from this function, such as tracing the result, or returning the value to be caught by higher level variable. The syntax of the function is function functionName (a1, a2, ...aN){ statement(s) };   Page 18 
  19. 19. Basic Actionscript  The application is: function multiply(a,b){ return a*b; }; To call the function, we just need to use the name of the function and the relevant parameters Multiplied = multiply(10,20);   Page 19 
  20. 20. Basic Actionscript  17. Symbol inside symbol The more complicated the animation / multimedia project, the bigger possibility to see many symbols inside symbol in Flash. You might see button inside movieclip, movieclip inside button, graphic inside button, and so on. There is no set rule when and where to use specific symbol inside another, but the understanding on what purpose each symbols are created might help - Graphic : This symbol is used if designer do not need to control the symbol using actionscript, as graphic symbol cannott have instance name - Button : This symbol is used if interaction between system and user is required - Movieclip : This symbol is used if there is a need to have loop animation or designer need to control symbol using actionscript Duplication and Removing Symbol By using actionscript, programmer can duplicate and remove movie clip. This function is very useful for game programming To duplicate movieclip duplicateMovieClip(“Name of movie clip”, “Name of new movie clip”, depth level); To remove movieclip removeMovieClip(“Name movie clip to remove”);   Page 20 
  21. 21. Basic Actionscript  18. Dragged object In order to make drag able object, Flash programmer needs to create button inside movieclip where the button receive the event whether it’s being pressed or released, and the user can drag. Movieclip will act as the container for that button To start the dragging function startDrag(Symbol to duplicate, lock center (true/false), left edge, top edge, right edge, bottom edge); To stop the dragging function stopDrag(); --- QU∑ST1ON? ---   Page 21 
  22. 22. Basic Actionscript  Flowchart Symbols A typical flowchart from older Computer Science textbooks may have the following kinds of symbols: Start and end symbols, represented as lozenges, ovals or rounded rectangles, usually containing the word "Start" or "End", or another phrase signaling the start or end of a process, such as "submit enquiry" or "receive product". Arrows, showing what's called "flow of control" in computer science. An arrow coming from one symbol and ending at another symbol represents that control passes to the symbol the arrow points to. Processing steps, represented as rectangles. Examples: "Add 1 to X"; "replace identified part"; "save changes" or similar. Input/Output, represented as a parallelogram. Examples: Get X from the user; display X. Conditional (or decision), represented as a diamond (rhombus). These typically contain a Yes/No question or True/False test. This symbol is unique in that it has two arrows coming out of it, usually from the bottom point and right point, one corresponding to Yes or True, and one corresponding to No or False. The arrows should always be labeled. More than two arrows can be used, but this is normally a clear indicator that a complex decision is being taken, in which case it may need to be broken-down further, or replaced with the "pre-defined process" symbol. A number of other symbols that have less universal currency, such as: A Document represented as a rectangle with a wavy base; A Manual input represented by parallelogram, with the top irregularly sloping up from left to right. An example would be to signify data-entry from a form; A Manual operation represented by a trapezoid with the longest parallel side at the top, to represent an operation or adjustment to process that can only be made manually. A Data File represented by a cylinder Note: All process symbols within a flowchart should be numbered. Normally a number is inserted inside the top of the shape to indicate which step the process is within the flowchart.   Page 22