flash8 lectures

Upload: vpmanimca

Post on 04-Jun-2018

218 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/13/2019 Flash8 Lectures

    1/100

  • 8/13/2019 Flash8 Lectures

    2/100

    Flash 8 Lecture Outline Copyright 2008 by Ken Slonneger Page 2

    Rectangle Tool (r)

    Shift drag gives a square

    PolyStar Tool: Options (polygon or star) in Properties Panel

    Pencil Tool (y)Shift drag gives 90 lines

    Properties: Change stroke size and kind of line

    Properties: Set Cap and Join

    Options: Straighten and Smooth

    Paint bucket Tool (k)

    In rectangle and ovals

    In drawn figuresPaint bucket may not fill if gaps occur in figure

    Ink Bottle Tool (s)

    Used to change the color of strokes in the same way the Paint Bucket is usedto change the color of fills.

    Provides access to the Properties Panel where the stroke style, color, and sizecan be changed and then the Ink Bottle can be clicked on the stroke of a shape.

    Can be used to add a stroke to a shape with no stroke.

    Pen Tool (p)

    Used to create Bzier curves, named for the mathematician Pierre Bzier.

    Polygonal Figures

    Alternate clicking and moving the mouse to create a polygon.

    Close the polygon by returning to the starting point or by

    Double clicking to end the drawing or

    Selecting another drawing tool for the Tools Panel to end the drawing.

    Curved FiguresClick to place an anchor point on the stage.

    Click at another place and drag the mouse to describe an invisible tangent lineto the curve being drawn from the anchor point.

    (You can start with a drag if you want to establish a starting tangent.)

    Clicking and dragging again continues the curve along another tangent line.

  • 8/13/2019 Flash8 Lectures

    3/100

    Flash 8 Lecture Outline Copyright 2008 by Ken Slonneger Page 3

    Just clicking also continues the curve, but clicking yet again continues the curvein a straight line.

    The drawing can be finished by closing the figure or by double clicking.

    Visual Help

    Show the progress of Pen tool drawings:Edit!Preferences!Drawing or

    Flash Professional!Preferences!Drawings (Macintosh)

    Check

    Show pen preview (for Pen Tool)

    Show solid points

    Show precise curves

    Editing Bzier Curves

    Choose the Subselection tool and alter articulation points, curve segments,

    or tangent lines orWith the Pen tool selected, hold down the control key and edit the curve.

    Pen States and Icons (Pen Tool chosen)

    Pen displays a smallxwhen it is simply over the stage.

    When the Pen hovers over an endpoint, it display an oto indicate that isan endpoint.

    When the Pen hovers over a corner point, it displays a - to indicate that clickingthis corner point deletes it.

    When the Pen is over a path between two points, it displays a + to indicatethat clicking here adds point to the path.

    When the Pen hovers over an existing point (not a corner), it displays a ^ toindicate that clicking that point turns in into a corner point.

    Brush Tool (b)

    Shift drag gives 90 lines

    Drawing will merge (same color) or cut out (different colors)

    Draws with fill color not the stroke color

    Line Tool (n)

    Shift drag gives 45 lines

    Reshape by dragging

  • 8/13/2019 Flash8 Lectures

    4/100

    Flash 8 Lecture Outline Copyright 2008 by Ken Slonneger Page 4

    Subselection Tool (a)

    Shows articulation points on line, brush, and pen drawings (and others)

    Free Transform Tool (q)

    Select what you want to transform

    Use handles in the transform selection to make changes

    Use the Transform Panel to make changes

    Eraser Tool (e)

    Erase any parts of a drawing by dragging eraser

    Lasso Tool (l)

    Select a figure that cannot be outlined by a rectangle

    Option: Polygonal lasso by clicking and double clicking at end

    Text Tool (t)

    Properties: Font, size, color, style, alignment

    Types: Static Text, Dynamic Text, Input Text

    Just start typing or

    Draw a rectangle to type inside

    Eyedropper Tool (i)

    Pick up a color to use as a fill with the Paint Bucket

    Hand Tool (h)

    Adjust the position of the stage

    Spacebar provides a temporary hand without changing the tool selection

    Zoom Tool (m,z)

    Options allow enlarge or reduce

    ctrl+= provides a temporary enlarge without changing tool selection

    ctrl+- provides a temporary reduce without changing tool selection

    Object Drawing (j)

    This Options makes each drawn figure a different object (no merge, no cut out).

  • 8/13/2019 Flash8 Lectures

    5/100

    Flash 8 Lecture Outline Copyright 2008 by Ken Slonneger Page 5

    Drawing Guides

    Need to have rulers: View !Rulers (alt+shift+ctrl+R)

    Drag guide down from ruler or to the right from ruler

    Show guide (default) View!Guides!Show Guides (ctrl+;)

    Snap to guides: View!Snapping!Snap to Guides (shift+ctrl+;)

    Guides are invisible in movie

    Grouping Drawn Objects

    Modify!Group (ctrl+g) and Modify!Ungroup (shift+ctrl+g)

    Make a duplicate of a drawn object: Edit !Duplicate (ctrl+d)Playing a Movie

    Play Enter

    Advance one frame .

    Move back one frame ,

    Create swffile and display movie ctrl+Enter

    Publish (create swfand html) File!Publish (ctrl+F12)

    Layers

    Shapes and figures drawn on separate layers do not merge or cut out.

    A layer may contain: a drawing

    a sound

    ActionScript (code)

    an animation

    Layers should be given descriptive names (double click on layer name, typea new name, and Enter).

    Add a layer

    Insert!Timeline!Layer or

    Press button on left below layer windowActive layer is highlighted with a pencil.

    Choosing a layer selects all the objects on that layer.

    Selecting an object on the stage may change the active layer.

  • 8/13/2019 Flash8 Lectures

    6/100

  • 8/13/2019 Flash8 Lectures

    7/100

  • 8/13/2019 Flash8 Lectures

    8/100

  • 8/13/2019 Flash8 Lectures

    9/100

    Flash 8 Lecture Outline Copyright 2008 by Ken Slonneger Page 9

    Create Shape Tween: Arrow with light green background

    Click on left Keyframe and select Shape from Properties panel Tween menu.

    Shape Hints

    Labeled a to z (up to 26 hints)

    Create a Shape HintModify!Shape!Add Shape Hint orctrl+shift+H

    Arrange shape hints on start drawing (yellow hints) and on end drawing (green hints)

    Place hints counter-clockwise from upper left

    Moving Object Along a Path

    Only possible with a Motion Tween

    StepsInsert Keyframes left and right.

    Choose layer and create a Motion Guide layer (three methods):

    Insert!Timeline!Motion Guide or

    Click second icon at bottom of Layers window

    Right click and choose Add Motion Guide

    Select Motion Guide layer.

    Draw a path on this layer (pencil, brush, or other drawing tool).

    Select View!Snap to Objects (the default setting).Place a Symbol at beginning of path on left Keyframe (snap center point).

    Place a Symbol at end of path on right Keyframe (snap center point).

    Create a Motion Tween on Motion Guide layer.

    Motion Guide layer may be locked and/or hidden.

    Editing Animation

    Drawing on stage can be changed only on Keyframes.

    Stretch or contract a tween: Double click on a Keyframe and drag either way.

    Reversing animation: Select animation layer and Modify !Timeline!Reverse frames.

    Add regular frames in a tween to slow animation down.

    Change frame rate to speed up or slow down animation.

  • 8/13/2019 Flash8 Lectures

    10/100

    Flash 8 Lecture Outline Copyright 2008 by Ken Slonneger Page 10

    Differences between Motion Tweens and Shape Tweens

    Motion: Works on Symbol instances, grouped drawings, and text objects.

    Shape: Works on drawn shapes and figures.

    Movement along a path only possible with a Motion Tween.

    Morphing a shape only possible with a Shape Tween.

    Movie Clip Symbols

    Insert!New Symbol (ctrl+F8)

    Name symbol and select Movie Clip for type

    Edit Symbol as a new movie with its own layers and tweens.

    Example

    Fat oval to a Skinny oval and then back to a Fat ovalCenter drawing (Cut and Paste)

    Create a tween from Fat oval to Fat oval so that the start and end pictures line up

    Create a Keyframe in the middle with the Skinny oval using Transform to shrink it

    Return to main scene (ctrl+e)

    Place several of the new Movie Clip Symbols on the stage

    Button Symbols

    Insert!New Symbol (ctrl+F8)

    Name symbol and select Button for type.

    Edit Symbol: Create graphics for

    Up state

    Over state

    Down state

    Hit state (maybe): a solid shape covering the button graphic

    Need a Keyframe for each state that we edit.

    Add a SoundImport a sound file

    File!Import!Import to Library (or Scene)

    Edit Button Symbol

    Put a Keyframe at Down state

    Place sound

  • 8/13/2019 Flash8 Lectures

    11/100

    Flash 8 Lecture Outline Copyright 2008 by Ken Slonneger Page 11

    Drag sound from Library toe Down frame or

    Select sound from Properties Panel for Button Symbol.

    Animated Button

    Place a Movie Clip Symbol on the Keyframe state that should be animated.

    Action for a Button

    Two possibilities

    Write ActionScript code (later)

    Use Window!Behaviors (shift+F3)

    Place a Button Symbol on the stage.

    Choose the Behaviors Panel.

    Click the plus sign and choose category and subcategory.

    Example !Web!Go to URLEnter a complete URL with protocol in window.

    Options: _self uses the same browser window

    _blank opens a new browser window

    Example

    Place text on stage: "Enter a web address: ".

    Use Text Tool with Input Text selected to place a text field on the stage and givethe field an instance name, say webAddress.

    Draw a rectangle around the text field with white fill.

    Place a Button Symbol on the stage and give it an instance name, say myButton.

    Create a new layer called Actions,

    Choose Actions layer, open Window!Actions (alt+F9), and type

    myButton.onRelease = function(){

    getUrl("http://"+webAddress.text, "_self");}

  • 8/13/2019 Flash8 Lectures

    12/100

  • 8/13/2019 Flash8 Lectures

    13/100

    Flash 8 Lecture Outline Copyright 2008 by Ken Slonneger Page 13

    Timeline Effects

    Flash provides eight Timeline Effects that act as shortcuts for creating animationsand drawings.

    Copy to Grid

    Insert!Timeline Effects!Assistants!Copy to Grid

    Options

    Grid Size

    Grid Spacing

    Examples: Matrix of stars, Matrix of spam cans

    Distributed Duplicates

    Insert!Timeline Effects!Assistants!Distributed DuplicatesOptions

    Number of Copies

    Offset Distance

    Offset Rotation

    Offset Start Frame (delay in frames for creating duplicates)

    Scaling (Exponential or Linear)

    Color, Final Color, and Alpha

    Example: Duplicate a die

    Blur

    Insert!Timeline Effects!Effects!Blur

    Options

    Effect Duration

    Resolution (number of copies displayed)

    Scale (factor by which object grows)

    Allow Horizontal BlurAllow Vertical Blur

    Direction of Movement

    Example: fire.jpg

  • 8/13/2019 Flash8 Lectures

    14/100

    Flash 8 Lecture Outline Copyright 2008 by Ken Slonneger Page 14

    Expand

    Insert!Timeline Effects!Effects!Expand

    Object expanded must be a Symbol

    Options

    Effect Duration

    Expand, Squeeze, or Both

    Direction of Movement

    Shift Group Center by

    Fragment Offset

    Change Fragment Size by

    Example: Beating heart

    Explode

    Insert!Timeline Effects!Effects!Explode

    Options

    Effect Duration

    Direction of Explosion

    Arc Size

    Rotate Fragments by

    Change Fragment Size by

    Final Alpha

    Examples: Herky, fire.jpg

    Drop Shadow

    Insert!Timeline Effects!Effects!Drop Shadow

    Options

    Color

    Alpha Transparency

    Shadow OffsetExamples: Herky, star

  • 8/13/2019 Flash8 Lectures

    15/100

    Flash 8 Lecture Outline Copyright 2008 by Ken Slonneger Page 15

    Transform

    Automatic Tweening

    Insert!Timeline Effects!Transform/Transition!Transform

    Options

    Effect Duration

    Change Position by

    Scale

    Rotate or Spin

    Change Color

    Final Alpha

    Motion Ease (Slow at Start or End)

    Example: star

    Transition

    Fade in/out and Wipe

    Insert!Timeline Effects!Transform/Transition!Transition

    Options

    Effect Duration

    Fade in/Fade out

    Wipe: object appears bit by bit along a line

    Direction

    Motion Ease (Slow at Start or End)

    Examples: fire.jpg and stars

    Notes on Timeline Effects

    Cannot edit Timeline Effects Symbols in the normal Symbol editing mode.

    Cannot add Keyframes on a layer with a Timeline Effect.

    To alter a Timeline Effect, select

    Modify!Timeline Effects!Edit Effect.To delete a Timeline Effect, select its layer and click

    Modify!Timeline Effects!Remove Effect.

  • 8/13/2019 Flash8 Lectures

    16/100

    Flash 8 Lecture Outline Copyright 2008 by Ken Slonneger Page 16

    Scenes

    Sequential animation can be organized into scenes to make development easier.

    Flash documents open with one scene, called "Scene 1".

    Open another scene (two ways)

    Insert!Scene

    Window!Other Panels!Scene (shift+F2) and click +at bottom of Scene Panel.

    Scenes can be renamed by double clicking on them in the Scene Panel.

    Drag scenes in the Scene Panel to reorder them.

    Changing from one scene to another scene:

    Select scene from Scene Panel or

    Choose scene from the menu below the movie clapperboard icon in the title bar.

    Delete a Scene: Choose it in Scene Panel and click on trash can.

    ActionScript Examples

    ActionScript is a programming language similar to JavaScript.

    An action (a code fragment) can be attached to a Keyframe or to an object (a symbol orcomponent).

    Example

    Create a Button Symbol.

    Give it an instance name, say "xyz".

    Select the button instance an open the Actions Panel usingWindow!Actions (alt+F9)

    Enter the following code in the Actions Panel:

    on (release){ stopDrag(); }

    on (press){ startDrag(xyz); }

    Create a Scene 2 with some animation, say a Transform Timeline Effect.

    Play the movie and note that Scene 1 moves directly into Scene 2.

    Return to Scene 1, choose frame 1, a Keyframe, and enter the following code:stop();

    Create another Button Symbol on Scene 1.

    Select the new button, open the Actions Panel (if not open), and enter this code:

    on (release){ gotoAndPlay("Scene 2", 1); }

    Try the movie now.

  • 8/13/2019 Flash8 Lectures

    17/100

    Flash 8 Lecture Outline Copyright 2008 by Ken Slonneger Page 17

    Custom Colors

    Consider the Color Mixer Panel, choosing Stroke icon or Fill icon.

    Note Option button on the right side of the title bar.

    Choose RGB (the default) or HSB .RGB

    Red-Green-Blue: eight bits each, represented as an unsigned byte, 0 to 255.

    HSB

    Hue-Saturation-Brightness: eight bits each, represented as an unsigned byte, 0 to 255.

    Hue: Color type (red, blue, etc.)

    Ranges from 0 to 360 degrees of a color wheel.

    red 0 yellow 59

    green 120 cyan 179blue 240 magenta 301

    Saturation: Intensity of color

    Ranges from 0% to 100%.

    0% is no color, a shade of grey between black and white.

    100% is an intense color.

    Brightness(or value): Amount of white in the color

    Ranges from 0% to 100%.

    0% is black.

    100% is white or a more or less saturated color.

    Color Selection Square (Rectangle): Click to choose a color.

    Luminance Slider: Shade of color

    Hexadecimal value: #000000 to #FFFFFF (RGB or HSB).

    Alpha Percentage: Ranges from 0% to 100%.

    Three Special Buttons: Black/White, No Color, and Swap Stroke and Fill.

    Select a Color from Elsewhere:

    Click and drag on the fill (or stoke) icon in the Color Mixer Panel.Color can be chosen from outside of Flash, say a Web page or an image.

    When the mouse (an eyedropper) is released, the color it is over becomes the fill color.

  • 8/13/2019 Flash8 Lectures

    18/100

    Flash 8 Lecture Outline Copyright 2008 by Ken Slonneger Page 18

    Save a Custom Color

    Options menu!Add Swatch

    Swatch is placed below existing swatches in the Color Swatches Panel.

    Alternatively, switch to the Color Swatches Panel and click in the region belowthe existing swatches (pointer is a paint bucket.).

    Click on Stroke icon or Fill icon

    Produces Color Swatches

    216 web-safe colors

    Swatches that we have added

    Some gradient swatches

    Color Picker Button (on right at top): Produces different panels on PCs and Macs.

    Color Swatches Panel

    Options Menu

    Delete swatch

    Web 216

    Sort by Color

    Save Colors

    Replace Colors

    GradientsColoring effect that blends bands of color into each other.

    Linear gradients: Straight left-to right, which can be rotated to otherorientations (see Gradient Transform tool).

    Radial gradients: Bands of color that begin in the center of a circle and radiate outward.

    Six gradient swatches reside on the Color Swatches Panel.

    Custom Gradients

    Enter the Color Mixer Panel.

    Choose Linear or Radial from the Type menu.

    Current gradient shows in rectangle at the bottom of the Panel.

    Above the sample is a narrow rectangle that acts as a slider with two pointers,a dark pointer and a light pointer.

    The pointers can be moved and even reversed.

    Change Pointer Color

    Select pointer (its arrowhead is black).

  • 8/13/2019 Flash8 Lectures

    19/100

  • 8/13/2019 Flash8 Lectures

    20/100

    Flash 8 Lecture Outline Copyright 2008 by Ken Slonneger Page 20

    ActionScript

    Code is executed when an event occurs:

    Movie clip is loaded.

    Keyframe on timeline is entered (a frame event).

    User clicks a button.

    We write an event handler to respond to the event with an action.

    Two groups of code

    Scripts for events that occur on the timeline.

    Scripts for object instances (buttons, movie clips, and components).

    Write code in

    Actions Panel (alt+F9)

    Script window (File!New and select ActionScript File) creates a file

    with an asextension.Actions Panel

    Script Pane: Write code here.

    Actions Toolbox: List of language elements.

    Script Navigator: Clickable tree showing elements that have scripts.

    Tab at bottom left of Script Pane shows the element the current script is attached to.

    Note that a timeline Keyframe with a script has a littleaon it.

    Add an item to a script (Double-click item or drag it to Actions Pane)

    Item from Actions ToolboxItem from menu below plus sign

    Options Menu

    Go to Line

    Find and Replace (ctrl+f)

    Auto Format (ctrl+shift+F)

    Check Syntax (ctrl+t)

    Print

    Hidden Characters (ctrl+shift+8)

    Preferences (ctrl+u)Import Script (ctrl+shift+I)

    Export Script (ctrl+shift+X)

    Example: Script for Frame 1.

    Button with a script.

    Script for Frame 20.

  • 8/13/2019 Flash8 Lectures

    21/100

    Flash 8 Lecture Outline Copyright 2008 by Ken Slonneger Page 21

    Global Variables

    Visible to every timeline and symbol in document.

    Creating:

    _global.gName = "Herky";

    Can be hidden by timeline variables and local variables in inner scopes, but canalways be accessed using_global.gName.

    Global variables cannot be typed because they are created without the varkeyword.

    Timeline Variables

    Visible to any script on that particular timeline (all layers).

    Creating:

    vartName = 66;

    Local Variables

    Visible only in the method where they are declared using var.

    Can hide Global variables and Timeline variables.

    Actionscript does not allow anonymous blocks (braces not belonging to a method).

    Declaring Variables

    Untyped (can be assigned any kind of value):

    varx;

    Typed:varn:Number;

    vars:String;

    With Initialization:

    vary = 123;

    varz:Boolean = true;

    Identifiers

    Names of variables, methods, classes, etc.Rule: A letter, underscore, or dollar sign followed by zero or more letters,

    digits, underscores, and dollar signs.

    Avoid the Reserved Words: 51+12 Keywords and 93 Class and Interface names.

    Avoid several predefined constants: true,false, null, undefined

  • 8/13/2019 Flash8 Lectures

    22/100

    Flash 8 Lecture Outline Copyright 2008 by Ken Slonneger Page 22

    Primitive Data Types

    Boolean

    Values: trueandfalse

    Number

    Digits with an optional sign in front, an optional decimal point, andan optional exponent using eor E.

    Number is an integer if no decimal point and no exponent.

    Number.MAX_VALUE: 1.79769e308

    Number.MIN_VALUE: 4.940546e-324

    String

    Sequence of Unicode characters delimited by quote symbols or apostrophes.

    undefined

    One value: undefined

    Value of uninitialized variables.

    null

    One value: null

    Means "no value".

    Default data type for all classes that define complex data types except Object.

    Complex Data Types

    Object

    Base class for all class definitions.MovieClip

    Its methods are used to to control Movie Clips.

    Array

    Used to type arrays.

    Void

    One value: void

    Used to designate the return type of methods that return no value.

  • 8/13/2019 Flash8 Lectures

    23/100

    Flash 8 Lecture Outline Copyright 2008 by Ken Slonneger Page 23

    Coercion

    In the absence of typed declarations, primitive type values are coerced if possible.

    If not possible, the value NaNis produces.

    Without typed declarations, ActionScript has dynamic typing and virtually notype checking.

    Examples

    varn = 12;

    varb = true;

    vars = "abc";

    varsd = "123";

    if(n) trace(true); // true

    elsetrace(false);

    if(s) trace(true); // trueelsetrace(false);

    trace(sd-5); // 118

    trace(s-5); // NaN

    trace(b+100); // 101

    With typed declarations, ActionScript has static typing so that errors are caughtby the compiler and reported in the Output Panel.

    Trace Method

    The method trace takes one parameter, converts it to a string, and prints it inthe Output Panel, which automatically appears.

    This Output Panel also appears if you script has a syntax error.The error will be reported in the Panel.

    Example: Prime Number Tester

    Scene 1

    A text string: Prime Number Tester

    A text string: Enter an integer

    An input text field (Text Tool) surrounded by a rectangle; instance nameof field is testNum.

    A Button Symbol with the message "Test Number" and an ActionScript:

  • 8/13/2019 Flash8 Lectures

    24/100

    Flash 8 Lecture Outline Copyright 2008 by Ken Slonneger Page 24

    on(release){

    varprime:Boolean;

    varnum:Number = Number(testNum.text);

    if(isNaN(num) || num==1){prime = false;

    }else{

    if(num == 2)prime = true;

    else if(num % 2 == 0)prime = false;

    else

    {prime = true;

    vardiv:Number = 3;

    while(div

  • 8/13/2019 Flash8 Lectures

    25/100

    Flash 8 Lecture Outline Copyright 2008 by Ken Slonneger Page 25

    Dynamic Text (and Input Text)

    Two ways to access contents:

    Instance name: abc

    Var: xyzBoth must be ActionScript identifiers.

    Access text

    abc.text = "Herky";

    xyz = "Hawk";

    Buttons on Properties Panel

    Selectable (can be copied and pasted)

    Render as HTML

    Show border around textExample

    Keyframes at 1, 20, and 40 that change the value of a dynamic text field.

    Input Text

    Additional field in Properties Panel: Maximum characters

    Movie Clip Control

    ActionScript code can be used to control the execution of a Movie Clip.

    Example1. From Keyframe 1 to Keyframe 20 have a word (Herky) move from off the stage to

    the center using a Motion Tween.

    2. From Keyframe 20 to Keyframe 30 have the word rotate once: Create a MotionTween in the Properties Panel and select Rotate: CW.

    3. On Keyframe 30 enter code: gotoAndPlay(20);What if we stretch or compress the tweens? Keyframe 20 may no longer be the beginningof the rotation action.

    4. Select Keyframe 20 and enter a Frame label "Start Loop". Change the code atKeyframe 30 to gotoAndPlay("Start Loop");

  • 8/13/2019 Flash8 Lectures

    26/100

    Flash 8 Lecture Outline Copyright 2008 by Ken Slonneger Page 26

    Buttons to Control Action

    Continue Example

    5. Create a new layer called Buttons so we do not affect the existing tweens.6. Create a Button Symbol and place two instances of it on the stage, one with label"Start" and one with "Stop".7. Add code for Start button

    on (press){ play(); }

    8. Add code for Stop buttonon (press){ stop(); }

    9. On Keyframe 1 of either layer (or a new one) enterstop();

    Put All Code on Timeline

    Continue Example

    10. Remove code from two buttons.11. Give each button an instance name, say startand stop.12. Add a layer called Actions.13. Enter this code on Keyframe 1 of the Actions layer.

    stop();

    start.onPress = function(){ play(); }

    stop.onPress = function(){ stop(); }

    Note that these two functions have no names; they are anonymous functions.

    Nested Movie Clips

    Flash documents typically have Movie Clip instances on their main timeline.

    These Movie Clips may have other Movie Clip instances inside of themselves, and so on.Example

    1. Create a spoked wheel; Draw a circle with one line bisecting it. Use Transform Panel,Rotate 60 with "Copy and apply transform" button.

    2. Change the color of several of the spokes so the motion can be seen.3. Convert drawing to a Movie Clip Symbol called Wheel.

  • 8/13/2019 Flash8 Lectures

    27/100

    Flash 8 Lecture Outline Copyright 2008 by Ken Slonneger Page 27

    4. Select the instance of Wheel and convert it to a Movie Clip Symbol calledRotatingWheel.

    5. Edit RotatingWheel, which contains a Wheel Symbol inside of it.6. Place a Keyframe at from 30 and create a Motion Tween, selecting CW from the Rotate

    menu in the Properties Panel.

    7. Place another RotatingWheel instance on the stage and draw a car over the two wheels.Select all and create a Movie Clip Symbol called Car.

    8. Add a new layer (Buttons) and place two instances of a Button Symbol on the newlayer.

    9. On one button enter the codeon (press){ stop(); }

    and try the movie (the wheels do not stop).

    10.

    On the other button enter the codeon (press){ play(); }

    11. Edit the Car Symbol. Give instance names to the two RotatingWheels, sayfrontWheeland backWheel. Give the Car instance a name, say car.

    12. Select the stop button and change the code toon (press){

    stop();car.frontWheel.stop();

    car.backWheel.stop();}

    13. Select the start button and start a new line below play();Click "Insert a target path" button (a circle over a cross) and choose car!backWheel.Then type "play();".Do the same with frontWheel to get the following code.

    on (press){

    play();this.car.frontWheel.play();

    this.car.backWheel.play();}

  • 8/13/2019 Flash8 Lectures

    28/100

    Flash 8 Lecture Outline Copyright 2008 by Ken Slonneger Page 28

    Bouncing Ball

    This example is designed to show how to complete the next project.

    Example

    1. Draw a green disk on the stage and convert it to a Movie Clip Symbol calledGreenBall.

    2. Movie Clip Symbols recognize a number of predefined properties such as _x, _y,_width, and _height. By altering the _xand _yproperties, we can cause the MovieClip Symbol to move across the stage.

    3. Just as Buttons respond to events (pressand release), Movie Clips respond to eventssuch as load, enterFrame, mouseDown, keyDown, among others.

    4. In the same way we handle Button events with an oncommand, we handle MovieClip events with an onClipEventcommand.

    5. Add the following code to the instance of GreenBall.onClipEvent (load)

    {

    speedX = 8;

    }

    onClipEvent (enterFrame) // executed as each frame is entered{

    _x = _x + speedX;}

    The ball will move horizontally across the stage, continuing off the right side.6. To get the ball to bounce against the right edge to the stage, change the code as follows.

    onClipEvent (enterFrame){

    _x = _x + speedX;

    if(_x >= 550){

    _x = 550; // bring back to the edgespeedX = -speedX; // change directions

    }

    Problem: Ball misses the edge by a little because the _xproperty is the registrationpoint of the Movie Clip instance (the plus sign) usually at the center of the object.

  • 8/13/2019 Flash8 Lectures

    29/100

    Flash 8 Lecture Outline Copyright 2008 by Ken Slonneger Page 29

    7. Assuming the registration point is at the center of the disk, change the code as follows.onClipEvent (enterFrame){

    _x = _x + speedX;

    if(_x + _width/2 >= 550){

    _x = 550 - _width/2;speedX = -speedX;

    }

    8. Now the ball bounces correctly on the right but continues forever moving to the leftoff the stage. Another problem is that if we change the dimensions of the stage, the550 numeral in the code may no longer be accurate. The next version of the codesolves both of these problems.

    onClipEvent (enterFrame){

    _x = _x + speedX;if(_x + _width/2 >= Stage.width){

    _x = Stage.width - _width/2;speedX = -speedX;

    }

    elseif(_x - _width/2

  • 8/13/2019 Flash8 Lectures

    30/100

    Flash 8 Lecture Outline Copyright 2008 by Ken Slonneger Page 30

    History Panel

    Records each action taken as you create a Flash document.

    Window!Other Panels!History (ctrl+F10)Default: History Panel stores 100 actions, a number that can be altered in Flash Preferences.Options Menu (or right button click)

    Replay Steps (also a button at bottom of panel).

    Copy Steps (also a button at bottom of panel).

    Save As Command (also a button at bottom of panel).

    Clear History (no undo).

    View (Arguments in Panel or JavaScript in Panel).

    Example

    Make a rectangle Movie Clip Symbol.Replay commands.

    Save As Command.

    Redo it.

    Add a text field.

    Choose View!Arguments in Panel.

    Choose View!JavaScript in Panel.

    Drag arrow in History Panel up.

    Then drag it back down.

    CopyPasteMove

    On History Panel choose View!Arguments in Panel.

    Place a colored disk on the stage.

    Select the disk.

    Edit!Copy (ctrl+c).

    Edit!Paste (shift+ctrl+V).

    Move object to the left about 100 pixels.Select last three commands from History Panel.

    Select Save As Command and name the command "CopyAndMove".

    Use the new command: Commands!CopyAndMove.

    This behavior is essentially the same as the Edit!Duplicate (ctrl+d) command.

  • 8/13/2019 Flash8 Lectures

    31/100

    Flash 8 Lecture Outline Copyright 2008 by Ken Slonneger Page 31

    Managing Commands

    Commands!Manage Saved Commands

    Select a command.

    The command may be renamed or deleted.

    CenterOnStage

    Select an object on the stage.

    In Align Panel, click To Stage modifier, click Align horizontal center,and click Align vertical center.

    Select the last two actions in the History Panel and Save As Command withthe name "CenterOnStage".

    This new command can be very useful.

    FiltersAccessed by a tab on the Properties Panel.

    Filters can be applied to a Symbol instance(Button or Movie Clip only) or to a text object.

    Procedure

    Open Filters Panel.

    Select the object to be altered.

    Select a filter to apply using the Add filter button menu.

    Use the Remove filter button to delete the chosen filter.

    The Add filter button also allows Remove All, Enable All, and Disable All.

    More than one filter may be applied to an object.

    The order of filter application may make a difference.

    Blur Filter

    This filter blurs the entire content of the instance.

    Parameters allow more or less blurring in the x or y direction.

    ExampleEnter some fairly large text, say "Flash Filters" with a sans serif 40 point font.

    Select the Blur filter.

    Place a Keyframe at frame 40 and change the Blur x and Blur y values to zero there.

    Place a motion tween between Keyframe 1 and Keyframe 40.

    Change Blur x and Blur y values to 70 at Keyframe 1.

    To reduce flicker in the tween, change the Quality value to High at both Keyframes.

  • 8/13/2019 Flash8 Lectures

    32/100

  • 8/13/2019 Flash8 Lectures

    33/100

    Flash 8 Lecture Outline Copyright 2008 by Ken Slonneger Page 33

    Example

    Create a Movie Clip Symbol from a blue rectangle.

    Apply the Bevel filter to an instance of the Symbol.

    Options: Blur x, Blur y, Strength, Quality, Angle, Distance, Type, and Knockout.

    Note: A negative distance reversed the bevel, which can be useful in showinga button press.

    Do the same thing with large colored text.

    Gradient Glow and Gradient Bevel Filters

    These filters are essentially the same as the Glow and Bevel filters except that they allowa gradient color for the effects.

    Adjust Color Filter

    This filter provides tools for manipulating the color properties of the instance.Since instances made from drawings or text objects can be manipulated by other means,this filter is useful primarily for instances formed from a bitmap picture.

    Slider Options: Brightness, Contrast, Saturation, and Hue.

    Try an example on ajpeg,gif,png, or some other picture type.

    Keypad Example

    This example illustrates the use of buttons to produce and process data.

    1. Create a new Button Symbol, called TheButton.

    Up: Red square with a Bevel filter, Blur x, Blur y: 10 and Quality: High).

    Over: Adjust Color filter, Brightness - 35.

    Down: Remove Adjust Color filter and change Bevel Distance to -5.

    2. Place four buttons on the stage in a horizontal row. Give them instance names,one, two, three, andfour. Call this layer "Buttons".

    3. On an new layer, called "Labels", above the Buttons layer, enter four digits,1, 2, 3, and 4, on top of the buttons using Arial 18 point bold black font.

    4. Build another Button Symbol, called ResetButton,

    Up: Blue rectangle with a Bevel filter, Blur x, Blur y: 8 and Quality: High).

    Over: Add a Glow filter with Strength: 190% and Color: White.

    Down: Remove Glow filter and change Bevel Distance to -5.

    5. Place one of the ResetButton Symbols on the stage with the instance name reset.

    6. On the Labels layer, enter "Reset" over the new button using Arial 18 pointbold white font.

  • 8/13/2019 Flash8 Lectures

    34/100

  • 8/13/2019 Flash8 Lectures

    35/100

    Flash 8 Lecture Outline Copyright 2008 by Ken Slonneger Page 35

    Conversion Functions

    These functions can be used to convert values from one primitive type to another.

    parseFloat : String"Number

    parseInt : String"

    NumberNumber : String"Number

    toString : Number"String (an instance method)String : Number"String

    Number : Boolean"Number

    Boolean : Number"Boolean

    Boolean : String"Boolean

    toString : Boolean"String (an instance method)

    String : Boolean"String

    The three conversion functions, Number, Boolean, and String, can be appliedto values of any type, resulting in some kind of value no matter what.

    Number Function

    Parameter Result

    undefined 0

    null 0

    Boolean 1 if true, 0 if false

    Number string Equivalent number if string is a properlyformatted number

    "Infinity" Infinity

    "-Infinity" -Infinity

    "NaN" NaN

    Other strings NaN

    Array NaNObject Result from applying

    valueOf() to the object

    Movieclip NaN

  • 8/13/2019 Flash8 Lectures

    36/100

    Flash 8 Lecture Outline Copyright 2008 by Ken Slonneger Page 36

    String Function

    Parameter Result

    undefined ""

    null "null"

    Boolean "true" if true, "false" if false

    NaN "NaN"

    Numeric value String representationof the number

    Infinity " Infinity"

    -Infinity " -Infinity"

    Array Comma-separated list of array values

    Object Result from applyingtoString() to the object

    Movieclip Path to movie clip instance

    Boolean Function

    Parameter Result

    undefined false

    null false

    NaN false

    0 false

    Infinity true

    -Infinity true

    Other numeric value true

    Empty string false

    Nonempty string true

    Array true

    Object true

    Movieclip true

  • 8/13/2019 Flash8 Lectures

    37/100

    Flash 8 Lecture Outline Copyright 2008 by Ken Slonneger Page 37

    Object Oriented Programming in ActionScript

    Classes

    Classes are syntactic units used to define objects. A class may contain instance variables, which will occur in each instance of the

    class, instance methods, which can be executed by objects of the class, and oneconstructor, which is called automatically when an object is created using new.

    Classes may also have class variables and class methods, but these belong to theclass itself and have no direct effect on the objects. ActionScript does not allowfinalas a modifier.

    A class must be defined in a file of its own using the name of the class as the filename and using asas the extenstion. The following example will be defined inthe fileMyClass.as.

    class MyClass

    {private var value : Number;

    public function MyClass(n : Number){ value = n; }

    public functionperform(m : Number) : Void{

    for(vark:Number = 1; k

  • 8/13/2019 Flash8 Lectures

    38/100

    Flash 8 Lecture Outline Copyright 2008 by Ken Slonneger Page 38

    The following code might appear in a Flash document. If so, the class fileMyClass.as must be in the same directory as the Flash document.

    var first : MyClass = newMyClass(5);

    varsecond : MyClass = newMyClass(3);first.perform(6);

    Prints:6 12 18 24 30

    second.perform(-4);

    Prints:-4 -8 -12

    Constructors

    A constructor is a method that is called automatically when an object is created. If the programmer supplies no constructor, a default constructor with noparameters is provided. This default constructor disappears if the programmer writes a constructor in the class. A class can have at most one constructor since ActionScript does not support the

    overloading of methods.

    In a constructor, super() calls a constructor of its superclass with the given parameters.

    Inheritance

    A new class can be defined as a subclass of an existing class using the extendskeyword. Then every object of the new subclass will have copies of the instance variables from its

    superclass (and its superclass and so on) as well as its own instance variables.

    It can also call instance methods defined in its superclass. Any method in the superclass can be overridden (re-defined) by writing a method

    in the subclass with the same signature.

    Any class definition without an extends clause is a subclass of Object by default. A variable of the superclass type may refer to an object of its class or an object of

    any of its subclasses.

    If an overridden method is called on a variable of the superclass, the class of the objectreferred to determines which version of the overridden method will be executed. Thisproperty is known as polymorphism or dynamic binding.

    In an instance method, the identifier thisrefers to the object, the receiver, that iscurrently executing the instance method.

    The identifier supercan be used to access instance methods (and variables) that havebeen overridden (and shadowed) in the subclass.

  • 8/13/2019 Flash8 Lectures

    39/100

  • 8/13/2019 Flash8 Lectures

    40/100

    Flash 8 Lecture Outline Copyright 2008 by Ken Slonneger Page 40

    Polymorphism Example

    Define a collection of classes representing geometric solids and including a method forcomputing their volumes.

    The superclass provides a String instance variable for identification and a volume methodto be overriden.

    classSolid{ // File: Solid.as

    private var kind : String;

    public functiongetKind() : String{ returnkind; }

    public functionvolume() : Number // This code is never executed{ return0.0; }

    }

    class Sphere extendsSolid{ // File: Sphere.asprivate varradius : Number;

    public function Sphere(r : Number){

    radius = r;kind = "Sphere";

    }

    public functionvolume() : Number{ return4.0/3.0*Math.PI*radius*radius*radius;}

    }

    classCube extendsSolid{ // File: Cube.as

    private varlength : Number;

    public functionCube(g : Number){

    length = g;kind = "Cube";

    }

    public functionvolume() : Number{ returnlength*length*length; }

    }

    classCone extendsSolid{ // File: Cone.as

    private var radius : Number;private varaltitude : Number;

  • 8/13/2019 Flash8 Lectures

    41/100

    Flash 8 Lecture Outline Copyright 2008 by Ken Slonneger Page 41

    public function Cone(r : Number, a : Number){

    radius = r;altitude = a;kind = "Cone";

    }public function volume() : Number{ returnMath.PI*radius*radius*altitude/3.0; }

    }

    To make use of Solid and its subclasses, create a Flash document with the followingActionScript code at Keyframe 1. Its file must be in the same directory as Solid.as, Sphere.as,Cube.as, and Cone.as. Save it before you try to test it.

    varlist : Array = newArray(6); // View as an array of Solid

    list[0] = newCube(10);

    list[1] = newCube(5);

    list[2] = newSphere(10);list[3] = newSphere(8);

    list[4] = newCone(3, 5);list[5] = newCone(8, 2);

    for(vark:Number=0; k

  • 8/13/2019 Flash8 Lectures

    42/100

    Flash 8 Lecture Outline Copyright 2008 by Ken Slonneger Page 42

    Interfaces

    An interface is a class-like mechanism that provides a specification of behavior (thesyntax) that classes must implement to make the behavior available. It contains onlypublic instance method headers (no bodies). Variables of any kind are not allowed.

    No objects can be instantiated directly from an interface. A class implementsaninterface by giving complete definitions of all of the methods in the interface. Then a variable declared of the interface type can be made to refer to such an object that

    implements the interface.

    Polymorphism can be performed with a group of classes that implement a commoninterface.

    interfacePrintable{ // File: Printable.as

    functionprintNum(n : Number) : Void;}

    classFirstImpl implementsPrintable{ // File: FirstImpl.as

    private varname : String;

    public functionFirstImpl(s : String){ name = s; }

    public functionprintNum(n : Number) : Void{

    trace(name + " prints " + n);}

    }

    classSecondImpl implementsPrintable{ // File: SecondImpl.as

    private varID : Number;

    public functionSecondImpl(n : Number){ ID = n; }

    public functionprintNum(n : Number) : Void{

    trace("Number" + ID + " prints " + n);}

    }

    To make use of Printable and its implementations, create a Flash document with thefollowing ActionScript code at its first Keyframe. It file must be in the same directory asPrintable.as, FirstImpl.as, and SecondImpl.as, and must be saved before it is tested.

    varfi : FirstImpl = newFirstImpl("Claude");

    varsi : SecondImpl = newSecondImpl(55);

  • 8/13/2019 Flash8 Lectures

    43/100

    Flash 8 Lecture Outline Copyright 2008 by Ken Slonneger Page 43

    varprinter1 : Printable = fi;

    varprinter2 : Printable = si;

    printer1.printNum(13);

    printer2.printNum(-99);

    Output

    Claude prints 13

    Number55 prints -99

    Symbols as Classes

    Movie Clip Symbols and Buttons Symbols can be viewed as classes that are instantiatedwhen they are placed on the stage.

    Example

    Create a green ball as a Movie Clip Symbol, called GreenBall.

    This operation implies a class definition of the form:

    classGreenBall extendsMovieClip{ }

    Put an instance of GreenBall on the stage, calling itgreen.

    We can provide properties (instance variables) and behavior (instance methods)for thegreeninstance using ActionScript in the Timeline.

    green.dx = 8;

    green.dy = 4;

    green.move = function(){

    green._x = green._x + green.dx;

    green._y = green._y + green.dy;}

    Control the animation using frame events attached to the main timeline Movie Clip,which is referred to by the global variable _root.

    _root.onLoad = function(){

    green.dx = 8;

    green.dy = 4;}

  • 8/13/2019 Flash8 Lectures

    44/100

    Flash 8 Lecture Outline Copyright 2008 by Ken Slonneger Page 44

    _root.onEnterFrame = function(){

    green.move();

    green.checkBounds();

    green.checkHit(); // dealt with later}

    The decision making for bouncing off of the edges of the stage is encapsulatedin an instance method checkBoundsfor the object namedgreen.

    Actually, the _rootobject is redundant, which onEnterFrameresponds to the maintimeline MoveClip.

    green.checkBounds = function() // Assumes registration point{ // of the ball is at its center

    if(green._x + green._width/2 >= Stage.width) // right edge{

    green._x = Stage.width - green._width/2;green.dx = -green.dx;

    }else if(green._x - green._width/2 = Stage.height) // bottom edge{

    green._y = Stage.height - green._height/2;

    green.dy = -green.dy;}else if(green._y - green._height/2

  • 8/13/2019 Flash8 Lectures

    45/100

    Flash 8 Lecture Outline Copyright 2008 by Ken Slonneger Page 45

    myStart.onPress = function(){

    green.dx = green.saveX;

    green.dy = green.saveY;

    }We have added four instance variables (dx, dy, saveX, saveY) to the object namedgreen,which also has access to instance variables (_x, _y,_width, _height, among others) inheritedfrom its superclass MovieClip.

    Add a blue Square Symbol instance to the stage. Make it 150 by 150 pixels.Call its instance square.

    Problem: We want the green ball to bounce off of the blue square.

    Hit Test

    Instance method in MovieClip:hitTest : Object#Boolean

    When the MovieClip squareand the objectgreenoverlap,

    square.hitTest(green) returns true.

    Add an instance method:

    green.checkHit = function(){

    if (square.hitTest(green)){

    green.dx = - green.dx;green.dy = - green.dy;

    }}

    Problem: This behavior is not the way a ball bounces.

    When the ball hits the left side or the right side of the square,only the dxvalue should reverse.

    When the ball hits the top side or the bottom side of the square,only the dyvalue should reverse.

    Solution: Test whether the ball is within |dx| distance of the left or right side ofthe square and whether it is within |dy| distance of the top or bottom of the square.

    The one-dimensional distance between two points is |x1- x2|.

    The new version of the checkHitinstance methods follows.

  • 8/13/2019 Flash8 Lectures

    46/100

    Flash 8 Lecture Outline Copyright 2008 by Ken Slonneger Page 46

    green.checkHit = function(){ // Assumes registration points are at centers of symbols

    if(square.hitTest(green)){

    if(Math.abs((green._x green._width/2)

    (square._x + square._width/2))

  • 8/13/2019 Flash8 Lectures

    47/100

  • 8/13/2019 Flash8 Lectures

    48/100

    Flash 8 Lecture Outline Copyright 2008 by Ken Slonneger Page 48

    Example: MySounds.fla

    Import the following sounds to the stage: crash.wavand Huntingdon.mp3.

    At Keyframe 1 play the crash sound.

    At Keyframe 10 (create it) make a Sound object for Huntingdon.mp3 and placefive buttons on the stage: start, stop, continu, louder, softer.

    Enter the follow code at Keyframe 10.

    snd = newSound();snd.attachSound("Huntingdon.mp3"); // Remember Export for ActionScriptsnd.setVolume(50);stop();

    start.onRelease = function(){

    snd.stop();snd.start();}

    stop.onRelease = function(){

    pos = snd.position/1000;

    snd.stop();}

    continu.onRelease = function(){ snd.start(pos); }

    louder.onRelease = function(){

    level = snd.getVolume();

    level = Math.min(100,level+5);

    snd.setVolume(level);

    trace(level);}

    softer.onRelease = function(){

    level = snd.getVolume();level = Math.max(0,level-5);

    snd.setVolume(level);

    trace(level);}

  • 8/13/2019 Flash8 Lectures

    49/100

  • 8/13/2019 Flash8 Lectures

    50/100

  • 8/13/2019 Flash8 Lectures

    51/100

    Flash 8 Lecture Outline Copyright 2008 by Ken Slonneger Page 51

    Handling Key Strokes

    ActionScript provides several ways to recognize key presses.

    Events shared by MovieClip and Button Classes

    onPress onDragOveronRelease onDragOut

    onReleaseOutSide onKeyDown

    onRollOver onKeyUp

    Example: MyEvents.fla

    Place a blue rectangle MovieClip instance on the center of the stage and call it box.

    To get the boxobject to recognize key presses, the focus needs to be set on the box.

    Enter the following ActionScript code at KeyFrame 1.box.useHandCursor = false; // otherwise cursor changes to a hand over box

    box.focusEnabled = true;

    Selection.setFocus(box);

    box.onRollOver = function(){ trace('RollOver'); }

    box.onRollOut = function(){ trace('RollOut'); }

    box.onReleaseOutside = function(){ trace('ReleaseOutSide'); }

    box.onRelease = function(){ trace('Release');

    Selection.setFocus(box);}

    box.onDragOver = function(){ trace('DragOver'); }

    box.onDragOut = function()

    { trace('DragOut'); }

    box.onPress = function()

    { trace('Press'); }box.onKeyDown = function(){ trace('KeyDown'); }

    box.onKeyUp = function(){ trace('KeyUp'); }

  • 8/13/2019 Flash8 Lectures

    52/100

  • 8/13/2019 Flash8 Lectures

    53/100

    Flash 8 Lecture Outline Copyright 2008 by Ken Slonneger Page 53

    Since any object can serve as the key listener, we can write the last part of the code usingthe _rootobject as the key listener.

    _root.onKeyDown = function(){

    trace("Key down");}

    _root.onKeyUp = function(){

    trace("Key up");trace(" Ascii = " + Key.getAscii());trace(" Code = " + Key.getCode());trace(" " + String.fromCharCode(Key.getCode()));

    }

    Key.addListener(_root);

    The Key class has 18 predefined constants for special keys.

    Key.BACKSPACE 8

    Key.SPACE 32

    Key.UP 38

    Key.DOWN 40

    Key.LEFT 37

    Key.RIGHT 39

    Key.SHIFT 16Key.TAB 9

    Key.ENTER 13

    Key.CONTROL 17

    Key.ESCAPE 27

    Key.END 35

    Key.CAPSLOCK 20

    Key.DELETEKEY 46

    Key.HOME 36

    Key.INSERT 45

    Key.PGDN 34

    Key.PGUP 33

  • 8/13/2019 Flash8 Lectures

    54/100

    Flash 8 Lecture Outline Copyright 2008 by Ken Slonneger Page 54

    Example: Arrows.fla

    Place an instance of a GreenBall Movie Clip Symbol on the stage and call itgreen.

    In this example we want to move the ball left and right, up and down, under controlof the four arrow keys on the keyboard.

    When the ball reaches the edge of the stage, have it disappear and then reappear onthe opposite edge of the stage.

    Enter the following ActionScript code at KeyFrame 1.

    onLoad = function(){

    green.dx = 5;green.dy = 8;

    }

    onEnterFrame = function(){

    if(Key.isDown(Key.LEFT)){

    newx = green._x-green.dx;

    if(newx = Stage.width){ newx = newx-Stage.width; }green._x = newx;

    }if(Key.isDown(Key.UP)){

    newy = green._y-green.dy;

    if(newy = Stage.height){ newy = newy-Stage.height; }green._y = newy;

    }}

  • 8/13/2019 Flash8 Lectures

    55/100

    Flash 8 Lecture Outline Copyright 2008 by Ken Slonneger Page 55

    Array Class

    Arrays in ActionScript are nonhomogenous since you can put values of anytype into them.

    They are dynamic in the sense that they can grow at runtime.

    There appears to be no way to type the elements of an array as a means of gettingstrong type checking for array elements.

    Array Creation

    vara : Array = newArray(); // an empty array

    b = newArray(4); // an array with 4 undefinedvalues

    c = [1, 2, 3, 4, 5]; // an array literal

    d = ["abc", 2+2, Math.PI, 'xyz']; // arrays can be nonhomogeneous

    e = newArray(["a", "b", "c"]);

    f = [[1,2,3],[4,5,6]]; // a two dimensional array

    g = newArray(['A','B'], ['Y','Z']); // a two dimensional array

    Output (result of toString())

    trace(a); none

    trace(b); undefined,undefined,undefined,undefined

    trace(c); 1,2,3,4,5

    trace(d); abc,4,3.14159265358979,xyz

    trace(e); a,b,ctrace(f); 1,2,3,4,5,6

    trace(g); A,B,Y,Z

    for(k=0; k

  • 8/13/2019 Flash8 Lectures

    56/100

    Flash 8 Lecture Outline Copyright 2008 by Ken Slonneger Page 56

    In the following definitions, the regular expression modifiers apply to theentire parameter.

    Array Instance Methods

    push(v : Object

    +

    ) : Number Adds one or more elements to the end of this arrayand returns the new length of the array.

    pop() : Object Removes the last element from this array andreturns the value of that element.

    unshift(v : Object+) : Number Adds one or more elements to the beginning ofthis array and returns the new length of the array.

    shift() : Object Removes the first element from this array andreturns the value of that element.

    reverse() : Void Reverses this array in place.

    slice(startindex : Number?,endindex : Number?) : Array

    Returns a new array consisting of a range ofelements from this array without modifying thisarray; the returned array includes the startindexelement and all elements up to but not includingtheendindexelement. Negative index values aremeasured from the end of the array.

    toString() : String Returns a string containing all of the elements ofthis array separated by commas.

    concat(v : Object*) : Array Concatenates the elements specified by parameterto the end of this array and returns it withoutchanging this array.

    join(delimiter : String?) : String Returns a string containing all of the elements ofthis array separated by the delimiter or bycommas if no delimiter.

    splice(startindex : Number,

    deleteCount : Number?,v : Object?) : Array

    Adds element to and removes elements from this

    array by modifying the array; deleteCountis thenumber of elements removed at the startindexposition; the elements specified by the thirdparameter are inserted at this point; the returnvalue is an array of the elements removed; if thedeleteCountparameter is omitted, all elementsfrom startindexto the end are delete.

  • 8/13/2019 Flash8 Lectures

    57/100

    Flash 8 Lecture Outline Copyright 2008 by Ken Slonneger Page 57

    Stack Behavior

    Usepushandpop.

    Queue BehaviorUsepushand shift.

    Examples

    h = c.concat();

    i = c.concat(e,e);

    trace(h); 1,2,3,4,5

    trace(i); 1,2,3,4,5,a,b,c,a,b,c

    trace(c); 1,2,3,4,5

    trace(c.join("; ")); 1; 2; 3; 4; 5

    trace(c.reverse()); 5,4,3,2,1

    trace(c); 5,4,3,2,1

    x = ["bat", "cat", "elk", "emu", "fox", "owl","rat", "yak"];

    y = x.slice(1,4);

    trace(y); cat,elk,emu

    trace(x); bat,cat,elk,emu,fox,owl,rat,yak

    z = x.splice(2, 3);

    trace(x); bat,cat,owl,rat,yak

    trace(z); elk,emu,fox

    w = x.splice(3, 0, z);

    trace(x); bat,cat,owl,elk,emu,fox,rat,yak

    trace(w); none

    The sliceand spliceoperations did not always work correctly for mewhen applied to the array resulting from an application of concat.

  • 8/13/2019 Flash8 Lectures

    58/100

  • 8/13/2019 Flash8 Lectures

    59/100

    Flash 8 Lecture Outline Copyright 2008 by Ken Slonneger Page 59

    We need to convert a Flash angle into the XY-coordinate system.

    Letflangbe the Flash angle.

    Let degreesbe the mathematical angle in the XY-coordinate system.

    Then degrees = flang - 90;

    Consider a vector in the XY-coordinate system.

    The motion is from A to B.

    Vector: angle = !

    speed = length of vector = distance from A to B.

    Translate to dx, dy

    sin != dy/speed

    cos != dx/speed

    dx = speed cos !

    dy = speed sin !

    Problem: Math.sin and Math.cos in ActionScript expect angles to be in radians.

    Conversion

    180 is equivalent to "radians

    degrees/180 = radians/"

    radians = " degrees / 180

  • 8/13/2019 Flash8 Lectures

    60/100

    Flash 8 Lecture Outline Copyright 2008 by Ken Slonneger Page 60

    Suppose a MovieClip object has the following properties:

    speed

    direction (in degrees)

    dx

    dySuppose the speedand directionare known. We want to compute the dxand dy.

    functionturn(mc : MovieClip){

    degrees = mc.direction - 90;

    radians = Math.PI * degrees / 180; // convert to radians

    mc.dx = mc.speed * Math.cos(radians);mc.dy = mc.speed * Math.sin(radians);

    }

    Problem: We turn the object by altering the direction property, say +5 or -5.If we want to display the direction, we want the value to be between 0 and 360.

    Each time we add or subtract 5, the result should be calculated modulo 360, whichis the positive remainder on dividing by 360.

    Note: The sine and cosine functions don't care about the magnitude of the angle; theywork just as well with negative angles and angles above 360.

    Problem: The remainder operator (%) in ActionScript does not compute the modulofunction correctly.

    Example: Divide by 4

    n n%4 mod(n, 4)5 1 14 0 03 3 32 2 21 1 10 0 0-1 -1 3-2 -2 2-3 -3 1

    -4 0 0-5 -1 3

    Solution: When the remainder is negative, add the divisor to it.

    functionmod(num, div){

    r = num % div;returnr

  • 8/13/2019 Flash8 Lectures

    61/100

    Flash 8 Lecture Outline Copyright 2008 by Ken Slonneger Page 61

    Example: TurningCar.fla

    Create a small MovieClip object that looks like a car seen from above.

    Place it on the stage pointing NorthEast with the instance name car.

    When the carobject reaches the edge of the stage, it continues on the opposite edge.

    Control: Left arrow Rotate car 5 counterclockwise.Right arrow Rotate car 5 clockwise.

    Up arrow Increase speed by 1.

    Down arrow Decrease speed by 1.

    The car has a maximum speed of 15. Of course, the minimum speed is 0.

    Enter the following ActionScript code at KeyFrame 1.

    car.speed = 0;car.direction = 45; // degrees

    car.maxSpeed = 15;

    onEnterFrame = function(){

    checkKeys();

    turn(car);

    move(car);}

    functioncheckKeys(){

    if(Key.isDown(Key.UP)){car.speed = Math.min(car.speed+1, car.maxSpeed);

    }

    if(Key.isDown(Key.DOWN)){

    car.speed = Math.max(car.speed-1,0);}

    if(Key.isDown(Key.RIGHT)){

    car.direction = mod(car.direction+5, 360);

    }if(Key.isDown(Key.LEFT)){

    car.direction = mod(car.direction-5, 360);}

    }

  • 8/13/2019 Flash8 Lectures

    62/100

    Flash 8 Lecture Outline Copyright 2008 by Ken Slonneger Page 62

    functionturn(mc : MovieClip){

    degrees = mc.direction - 90;radians = Math.PI *degrees / 180;mc.dx = mc.speed *Math.cos(radians);mc.dy = mc.speed *Math.sin(radians);

    }

    functionmove(mc : MovieClip){

    mc._x = mc._x + mc.dx;mc._y = mc._y + mc.dy;

    mc._rotation = mc.direction;

    if(mc._x > Stage.width){ mc._x = 0; }

    if(mc._x < 0){ mc._x = Stage.width; }

    if (mc._y > Stage.height){ mc._y = 0; }

    if(mc._y < 0){ mc._y = Stage.height; }

    }

    functionmod(num, div){

    r = num % div;returnr

  • 8/13/2019 Flash8 Lectures

    63/100

    Flash 8 Lecture Outline Copyright 2008 by Ken Slonneger Page 63

    Put this code in a Flash document.

    b = newBox();

    b.size = 10; // legal now

    When a class has the dynamicmodifier, properties may be added to its objects

    outside of its class definition.Recommendation: Dynamic classes are considered poor OOP design, although thisusage is found in Flash code frequently. A better approach would be to use a subclassof the class to add a property.

    The MovieClip, Array, and Object classes are defined as dynamic.

    Subclasses of dynamic classes are normally dynamic.

    But subclasses of MovieClip and Object are notdynamic, by default.

    Kinds of Variables in Classes

    property An instance variable defined in the class and found in eachobject of the class.

    class property A class variable defined in the class and belonging to theclass itself.

    dynamic property An instance variable defined outside of the class definition;it belongs to only one object, the one it is defined for.

    Visibility Modifiers

    public and private

    No modifier on a member of a class means that it is public.

    ActionScript does not allowfinalas a modifier.

    Viewing Properties

    Change the Box class to read as follows.

    dynamic classBox{

    varwidth : Number = 25;

    varheight : Number = 50;

    vardescription : String = "red box";}

    Consider this ActionScript code in a Flash document.

    b = newBox();

    trace(b.width); // prints 25

    trace(b.height): // prints 50

  • 8/13/2019 Flash8 Lectures

    64/100

    Flash 8 Lecture Outline Copyright 2008 by Ken Slonneger Page 64

    Alternate syntax

    trace(b["width"]); // prints 25

    fld = "height";

    trace(b[fld]); // prints 50Contrast Syntax

    With the syntax b.widthand b.height, the field (property) name must be static,which means it is known to the compiler).

    With the syntax b["width"]and b[fld], the field (property) name can be dynamic,which means it may not be known until runtime.

    Object Literals

    ActionScript allows literal expressions that represent Object objects with dynamicproperties belong to this new object only.

    varob : Object = {x:33, y:44, color:"blue", visible:false};

    Displaying the Properties

    for(prop : String inob){

    trace("--------------------------------------------");

    trace("Property name: " + prop);

    trace("Property value: " + ob[prop]);}

    trace("--------------------------------------------");

    Output

    -----------------------------------------Property name: xProperty value: 33-----------------------------------------Property name: yProperty value: 44-----------------------------------------Property name: color

    Property value: blue-----------------------------------------Property name: visibleProperty value: false-----------------------------------------

    Note: The ob[prop]syntax works only with dynamic properties.

  • 8/13/2019 Flash8 Lectures

    65/100

    Flash 8 Lecture Outline Copyright 2008 by Ken Slonneger Page 65

    Array Example

    playOffs = newArray();

    playOffs.push("Red Sox", "Indians", "Rockies", "Diamondbacks");

    for(team inplayOffs){

    trace(playOffs[team]);}

    Create a MovieClip Instance Dynamically

    Create a MovieClip Symbol called Ball.

    In the Properties window (Option menu or right-click in the Library Panel), select

    Export for ActionScript

    Use the MovieClip instance method attachMovieon the _rootobject.

    public attachMovie(symbolLinkage : String, // name of the class (symbol)

    instanceName : String,

    depth : Number,

    initObject : Object?) : MovieClip

    The depthparameter is an integer that describes the level at which the instance will beplaced. Each instance on the stage must lie on a unique level. Either maintain a countervariable to ensure that different instances created dynamically lie on difference levelsor use the instance methodgetNextHighestDepth.

    The initObjectparameter can be used to initialize the instance coming into existence,say by an anonymous object literal such as { _x : 100, _y : 150 }.

    Removing a MovieClip

    Global class method

    removeMovieClip(instanceName);

    MovieClip instance method

    instanceName.removeMovieClip():

    Returning to the example

    Create an instance of Ball called theBall._root.attachMovie("Ball", "theBall", 10); or attachMovie("Ball", "theBall", 10);

    Position the ball.

    theBall._x = 200;

    theBall._y = 130;

  • 8/13/2019 Flash8 Lectures

    66/100

    Flash 8 Lecture Outline Copyright 2008 by Ken Slonneger Page 66

    eval Function

    This function can be used to build an identifier dynamically that refers to an instance.

    eval(expr : String) : Object

    If expris a variable identifier or a property identifier (as a String), the value of thevariable or property is returned as the result.

    If the item named in exprcannot be found, undefinedis returned.

    Note that the evalfunction only returns an R-value.

    Suppose we have three MovieClip objects, box1, box2, and box3.

    Rotate each to 45.

    for(k=1; k

  • 8/13/2019 Flash8 Lectures

    67/100

  • 8/13/2019 Flash8 Lectures

    68/100

    Flash 8 Lecture Outline Copyright 2008 by Ken Slonneger Page 68

    functionmove(){

    _x = _x+dx;

    _y = _y+dy;}

    functionstop(){ dx = dy= 0; }

    function start(){

    dx = xspeed;dy = yspeed;

    }

    functioncheckBounds(){

    if(_x + _width/2 >= Stage.width){ dx = -dx; }

    if(_x - _width/2 = Stage.height){ dy = -dy; }

    if(_y - _height/2

  • 8/13/2019 Flash8 Lectures

    69/100

    Flash 8 Lecture Outline Copyright 2008 by Ken Slonneger Page 69

    Gravity

    Gravity is a constant force acting to accelerate the downward velocity (dy) of an objectover time.

    Since the positive direction ofyis down, we simply need to add a positive constant

    to the downward velocity dyin each frame, the measure of time in Flash.Acceleration = Change in Velocity

    Velocity = Change in Position

    Relationships

    position = velocity time + initialPosition

    velocity = acceleration time + initialVelocity

    Consider two points in time, t1and t2.

    p2= v t2+ initialPosition

    p1= v t1+ initialPosition

    Subtract

    p2- p1= v (t2- t1)

    Let t2= t1+ 1.

    p2= p1+ v

    This corresponds to the command _x = _x + dx.

    v2= a t2+ initialVelocity

    v1= a t1+ initialVelocity

    Subtract

    v2- v1= a (t2- t1)

    Let t2= t1+ 1.

    v2= v1+ a

    This corresponds to the command dx = dx + a.

    Note: Both velocity and acceleration may be functions of time and not just constants.

    Example: Gravity.fla

    Create a MovieClip Symbol Ball and place one instance of it on the stage with thename ball.

    Enter the following ActionScript code at KeyFrame 1.

    ball.dx = 10;

    ball.dy = 5;

    gravity = 3;

  • 8/13/2019 Flash8 Lectures

    70/100

  • 8/13/2019 Flash8 Lectures

    71/100

    Flash 8 Lecture Outline Copyright 2008 by Ken Slonneger Page 71

    Example: GravityTrace.fla

    Create a MovieClip Symbol in the shape of a cannon and place an instance of it inthe lower left corner of the stage with the instance namegun.

    Create another MovieClip Symbol that is a small black disk and place an instance

    of it behind the cannon with the instance name bullet.Place two dynamic text fields near the bottom edge of the state with the variablenames (Var: field) bullet.directionand bullet.speed.

    Enter the following ActionScript code at KeyFrame 1.

    gun.direction = 0;

    gun.charge = 0;

    gravity = 0.5;

    onEnterFrame = function()

    { checkKeys(); move(bullet);}

    functioncheckKeys(){

    if(Key.isDown(Key.LEFT)){

    clear();gun._rotation = gun.direction = gun.direction - 2;

    }

    if(Key.isDown(Key.RIGHT))

    { clear();gun._rotation = gun.direction = gun.direction + 2;

    }

    if(Key.isDown(Key.UP)){

    clear();gun.charge = gun.charge + 5;

    }

    if(Key.isDown(Key.DOWN)){

    clear();gun.charge = gun.charge - 5;

    }

    if(Key.isDown(Key.SPACE)){

    bullet._x = gun._x;bullet._y = gun._y;

  • 8/13/2019 Flash8 Lectures

    72/100

    Flash 8 Lecture Outline Copyright 2008 by Ken Slonneger Page 72

    bullet.speed = gun.charge;

    bullet.direction = gun.direction;

    clear();

    lineStyle(2,0x000000,100);

    moveTo(gun._x, gun._y);

    turn(bullet);}

    }

    functionturn(mc){

    degrees = mc.direction -90;radians = degrees / 180 *Math.PI;mc.dx = mc.speed*Math.cos(radians);mc.dy = mc.speed*Math.sin(radians);

    }

    functionmove(mc){

    mc._x = mc._x + mc.dx;mc._y = mc._y + mc.dy;

    _root.lineTo(mc._x, mc._y);

    if((mc._x > Stage.width) || (mc._x < 0) || (mc._y > Stage.height) ){

    mc._x = -100; //stop mc and move it off stagemc._y = -100;

    mc._speed = 0;mc.dx = 0;mc.dy = 0;lineStyle(0,0x000000,0); //turn off line drawing

    }

    mc.dy = mc.dy + gravity;}

    Notes

    A line drawing traces the path of the cannon ball using the methods lineStyle,moveTo, and lineTo.

    The line drawing that traces the cannon ball path is erased (clear) whenever a keyis recognized by the code.

    If the cannon passes through the left edge, the right edge, or the bottom of the stage,it is moved to position (-100, -100), which is off the stage, and it is stopped.

    The top edge of the stage is no barrier at all. The cannon ball passed off the topof the stage and then returns if it has not met one of the edges.

  • 8/13/2019 Flash8 Lectures

    73/100

    Flash 8 Lecture Outline Copyright 2008 by Ken Slonneger Page 73

    Using Dynamically Created Objects and an Array

    Example: CursorTrail.fla

    Create a MovieClip Symbol called Cursor that is a small red disk with a black border.

    Enter the following ActionScript code at KeyFrame 1.

    onLoad = function(){

    for(vark=0; k 10) trail.shift(); // keep only last 10 positions

    for(vark=0; k

  • 8/13/2019 Flash8 Lectures

    74/100

    Flash 8 Lecture Outline Copyright 2008 by Ken Slonneger Page 74

    Example: TimeTracer.as

    Create an ActionScript file containing the following code.

    The method startTimeDisplaytakes a reference to a dynamic text field as its parameter.

    Note that newDate().toString()returns a string of the form:

    Tue Nov 27 15:10:45 GMT-0600 2007

    The displayTime method puts a new string of the form Tue Nov 27 15:10:45into thedynamic text field every second.

    classTimeTracer{

    private vartimerID : Number;

    public functionstartTimeDisplay(disp) : Void{

    varbegunAt : String = newDate().toString();

    trace("Timer started at " + begunAt);timerID = setInterval(displayTime, 1000);

    functiondisplayTime() : Void{

    vars : String = newDate().toString();

    varn : Number = s.indexOf("GMT");

    disp.text = s.substring(0, n);}

    }

    public functionstopTimeDisplay() : Void{

    clearInterval(timerID);}

    }

    Using TimeTracer: TryTimeTracer.fla

    Create a dynamic text field, centered on the stage, with the instance name timeField.

    Use a large font for the field.

    Enter the following code at KeyFrame 1:

    vartt : TimeTracer = newTimeTracer();tt.startTimeDisplay(timeField);

    Enter the following code at KeyFrame 100:

    tt.stopTimeDisplay();

    stop();

  • 8/13/2019 Flash8 Lectures

    75/100

    Flash 8 Lecture Outline Copyright 2008 by Ken Slonneger Page 75

    Using TimeTracer for an Analogue Clock

    Add two methods to TimeTracer.as.

    public functiongetHour() : Number{

    return newDate().getHours(); // note names of Date methods}

    public functiongetMinute() : Number{

    return newDate().getMinutes();}

    Flash Document: Clock.fla

    Draw a clock face on the stage. Create arrow shaped MovieClip Symbols for the minutehand (minuteHand) and the hour hand (hourHand) with the rotation points at the base ofthe arrows.

    Enter the following ActionScript code at KeyFrame 1.

    var tt : TimeTracer = newTimeTracer();

    tt.startTimeDisplay(null);

    onEnterFrame = function(){

    minute = tt.getMinute();

    minuteHand._rotation = minute*6;

    hourHand._rotation = (tt.getHour()%12)*30 + minute/2 ;}

    Using Frame Count for Timing: WordServer.fla

    In this example, the words of a sentence are displayed on the screen one at a time witha uniform delay.

    Place a dynamic text field at the center of the stage using a large font, with the instancename display.

    Enter the following ActionScript code at KeyFrame 1.

    onLoad = function(){

    sentence = "Imagination is more important than knowledge";wordList = sentence.split(" "); // produces an array of strings

    wordNum = 0;

    frameDelay = 12;

    frameCount = frameDelay; // prime for first word}

  • 8/13/2019 Flash8 Lectures

    76/100

  • 8/13/2019 Flash8 Lectures

    77/100

  • 8/13/2019 Flash8 Lectures

    78/100

    Flash 8 Lecture Outline Copyright 2008 by Ken Slonneger Page 78

    with Command

    The with command specifies an object in whose context a group of commandsis executed.

    This context may apply to variables and methods in the group of commands.

    with(obj : Object){commands

    }

    Example: FillWith.fla

    Enter the following ActionScript code at KeyFrame 1.

    createEmptyMovieClip("mc", 10);

    with(mc){

    lineStyle(4, 0x000000, 100);beginFill(0xff00cc);moveTo(50, 50);lineTo(150, 50);lineTo(150, 200);lineTo(50, 200);

    endFill();}

    Example: Lines.fla

    Enter the following ActionScript code at KeyFrame 1.

    createEmptyMovieClip("lines", 10);

    lines.moveTo(Stage.width/2, Stage.height/2);

    lines.lineStyle(6, 0xffff00, 100);

    onMouseDown = function(){

    lines.lineTo(_xmouse, _ymouse);}

    onEnterFrame = function() // moves the MovieClip object{

    if(Key.isDown(Key.SPACE)){lines._x = lines._x + 5;lines._y = lines._y + 5;

    }}

  • 8/13/2019 Flash8 Lectures

    79/100

    Flash 8 Lecture Outline Copyright 2008 by Ken Slonneger Page 79

    Example: Curves.fla

    Enter the following ActionScript code at KeyFrame 1.

    createEmptyMovieClip("curves", 10);

    varframeCount = 0;onEnterFrame = function(){

    color = (100000*frameCount) % 0x1000000; // 0x000000 to 0xffffffwith(curves){

    lineStyle(2, color, 100);moveTo(100, 200);curveTo(_xmouse, _ymouse, 450, 200); // curve from (100,200) to (450,200)

    }frameCount++;

    }onMouseUp = function(){

    curves.clear();}

    Example: Snowflakes.fla

    Set the background of the stage to a deep blue.

    Enter the following ActionScript code at KeyFrame 1.

    numSnowflakes = 50;

    for(vark=0; k

  • 8/13/2019 Flash8 Lectures

    80/100

  • 8/13/2019 Flash8 Lectures

    81/100

    Flash 8 Lecture Outline Copyright 2008 by Ken Slonneger Page 81

    Duplicating a Movie Clip

    The class MovieClip has an instance method that can be used to duplicate a MovieClipobject, the receiver of the method.

    duplicateMovieClip(instanceName : String,depth : Number, initObj : Object?) : MovieClip

    Note: There are two global functions for duplicating a MovieClip object, which shouldnot be confused with this instance method.

    Example: Duplicate.fla

    Enter the following ActionScript code at KeyFrame 1.

    createEmptyMovieClip("box", 0);

    varw : Number = 400;

    varh : Number = 20;with(box){

    lineStyle(4, 0x0000, 100);

    beginFill(0x66ffff);

    moveTo(50, 40);

    lineTo(50+w, 40);

    lineTo(50+w, 40+h);

    lineTo(50, 40+h);

    lineTo(50, 40);

    endFill();}

    trace(box);

    varspacer : Number = 5;

    varduplicate : MovieClip;

    for(vark:Number=1; k

  • 8/13/2019 Flash8 Lectures

    82/100

    Flash 8 Lecture Outline Copyright 2008 by Ken Slonneger Page 82

    Example: Particle.fla

    Create a Movie Clip Symbol as a 80 by 80 pixel disk at the center of the stagewith a white to gray radial gradient.

    Call the instance on the stageparticle.

    Enter the following ActionScript code at KeyFrame 1.

    for(vark : Number = 1; k

  • 8/13/2019 Flash8 Lectures

    83/100

    Flash 8 Lecture Outline Copyright 2008 by Ken Slonneger Page 83

    2. Load the information.

    lv.load("data"); // local file

    lv.load("http://www.cs.uiowa.edu/~slonnegr/flash/data"); // web site

    3. Notification of completed loading.

    lv.onLoad = function(success){ trace("Load Complete: " + success); }

    The Boolean parameter successwill be trueif the load was successful.

    4. Display the values.

    The names in the data file become instance variables in the LoadVars object lv.

    trace(lv.username);

    Example: LoadVars.fla

    Place two buttons on the stage with the labels LOADVARS and SHOWVARS andthe instance names loadand show.

    Enter the following ActionScript code at KeyFrame 1.

    varready = false;

    load.onRelease = function(){

    lv = newLoadVars();

    lv.load("data"); // OR

    // lv.load("http://www.cs.uiowa.edu/~slonnegr/flash/data");

    lv.onLoad = function(success){

    trace("Load Complete: " + success);ready = success;

    }}

    show.onRelease = function(){

    if(ready){

    trace(lv.message); trace(lv.color);

    trace(lv.passwd); trace(lv.username);}elsetrace("Variables not loaded yet.");

    }

  • 8/13/2019 Flash8 Lectures

    84/100

  • 8/13/2019 Flash8 Lectures

    85/100

    Flash 8 Lecture Outline Copyright 2008 by Ken Slonneger Page 85

    Example: SendData.fla

    Enter the following ActionScript code at KeyFrame 1.

    sendVars = newLoadVars();

    sendVars.username = "Claude";sendVars.age = 17;

    sendVars.color = "gray";

    sendVars.send("http://r-lnx233.cs.uiowa.edu:8888", "_self", "GET");

    OR

    sendVars.send(

    "http://webdev.divms.uiowa.edu/slonnegr-tomcat4/ShowParams",

    "_self", "GET");

    When the request is sent to a Java server program running at port 8888 on the computerr-lnx233.cs.uiowa.edu, the result is the following web page.

  • 8/13/2019 Flash8 Lectures

    86/100

    Flash 8 Lecture Outline Copyright 2008 by Ken Slonneger Page 86

    When the request is sent to a Java Servlet running on the computer webdev.divms.uiowa.edu,the result is the following web page.

    I could not get a POST request to work correctly.

    Shared Objects

    Flash has a mechanism that allows an executing Flash movie to store and/or retrievelimited amounts of data on the user's computer similar to the way browser cookies

    store data for web pages.Some possible uses of shared objects:

    Store the user name and password on the local computer so it need not be typedby the user each time it is requested.

    Store the high scores from the games played by the user on this machine. Store user preferences between sessions. Store local copies of data obtained from a web site so that web accesses can be

    minimized.

    The process begins with the creation of a StoredObject object using the class methodgetLocal.

    varso : SharedObject = SharedObject.getLocal("foobar");

    or

    varso : SharedObject = SharedObject.getLocal("foobar", "/");

    In the first version, the information stored can be accessed only by the same executingFlash movie.

  • 8/13/2019 Flash8 Lectures

    87/100

    Flash 8 Lecture Outline Copyright 2008 by Ken Slonneger Page 87

    In the second version, the information stored can be accessed by all executingFlash movies on a particular computer.

    By specifying other path names, accessibility falls between these two extremes.

    The information to be stored and retrieved is accessed through an instance variable databelonging to the SharedObject object.

    Example

    Create a Flash document SharedObjectSave.flawith the following code at KeyFrame 1.

    varso:SharedObject = SharedObject.getLocal("foobar","/");

    so.data.nums = newArray(121, 143, 165, 187);

    so.data.isHungry = false;

    so.data.userName = "Claude";

    so.data.ob = { x:33, y:55, z:77};

    so.flush();

    Theflushcommand forces the values to be saved locally, but closing the swffile will havethe same effect.

    Create another Flash document SharedObjectRecall.flawith the following code atKeyFrame 1.

    varso : SharedObject = SharedObject.getLocal("foobar","/");

    trace(so.data.nums);

    trace(so.data.isHungry);

    trace(so.data.userName);

    trace(so.data.ob.x);

    trace(so.data.ob.y);

    trace(so.data.ob.z);

    Output

    121,143,165,187falseClaude33

    5577

    Observe that information is stored in the local file using name-value pairs similarto attributes for the property dataof the SharedObject object.

  • 8/13/2019 Flash8 Lectures

    88/100

    Flash 8 Lecture Outline Copyright 2008 by Ken Slonneger Page 88

    All the information stored in a particular SharedObject can be removed using the clearinstance method.

    so.clear();

    Example: SharedObjectLogin.fla

    Create two input text fields with the instance names myLoginand myPasswdand labelthem appropriately.

    Create four button with instance names saveButton, loadButton, clearButton, andresetButtonand with labels "Save", "Load", "Clear", and "Reset", respectively.

    Enter the following ActionScript code at KeyFrame 1.

    varmySO:SharedObject = SharedObject.getLocal("myCookie");

    saveButton.onRelease = function(){

    mySO.data.myLoginData = myLogin.text;

    mySO.data.myPassword = myPasswd.text;mySO.flush();

    }

    loadButton.onRelease = function(){

    myLogin.text = mySO.data.myLoginData;

    myPasswd.text = mySO.data.myPassword;}

    clearButton.onRelease = function(){

    mySO.clear();}

    resetButton.onRelease = function(){

    myLogin.text = "";

    myPasswd.text = "";}

    When this movie is executed, we must click in each of the text fields before typing.

    The problem of automatically moving the focus to the first text field and using the

    tab key to move from field to field seems to have no easy solution.Here is a solution using the left and right arrow keys to put the focus in one or theother text field. It makes use of the Selection class.

  • 8/13/2019 Flash8 Lectures

    89/100

    Flash 8 Lecture Outline Copyright 2008 by Ken Slonneger Page 89

    Enter the following ActionScript code above the previous code.

    varlistener : Object = newObject();

    listener.onKeyDown = function(){

    if(Key.isDown(Key.LEFT)){

    Selection.setFocus(myLogin);}if(Key.isDown(Key.RIGHT)){

    Selection.setFocus(myPasswd);}

    }

    Key.addListener(listener);

    Creating Text Fields Dynamically

    The MovieClip class has an instance method that can be used to create a text fielddynamically.

    createTextField(instanceName : String,

    depth : Number,

    x : Number, y : Number, // position of upper-left corner

    width : Number, height : Number) : TextField

    A TextField object has a number of properties that can be altered to customize the text field.

    Here are some of them.Property Default Value

    type "dynamic"

    border false

    background false

    multiline false

    embedFonts false

    selectable true

    wordWrap truevariable null

    maxChars null

  • 8/13/2019 Flash8 Lectures

    90/100

    Flash 8 Lecture Outline Copyright 2008 by Ken Slonneger Page 90

    A text field created using the createTextFieldmethod receives a default TextFormatobject with the following settings (not default values for TextFormat).

    Property Setting Comments

    font "Times New Roman" "Times" on Mac OSsize 12

    color 0x000000

    bold false

    italic false

    underline false

    url "" hyperlink for text in field

    target "" _self, _blank

    align "left" "center, "right", "justify"leftMargin 0

    rightMargin 0

    indent 0

    leading 0

    blockIndent 0

    bullet false

    kerning false

    display block tabStops [ ] empty array

    These values my be altered by creating a new TextFormat object, defining values forsome of the properties, and then attaching the TextFormat object to the TextField object.

    createTextField("myTF", 99, 100, 50, 300, 40);

    myTF.text = "Nobody goes there anymore. Its too crowded.";

    myFmt = newTextFormat();

    myFmt.size = 24;

    myFmt.color = 0x00ffff; // cyan

    myFmt.bold = true;

    myTF.setTextFormat(myFmt);

  • 8/13/2019 Flash8 Lectures

    91/100

    Flash 8 Lecture Outline Copyright 2008 by Ken Slonneger Page 91

    Example: FlyingText.fla

    This Flash document creates and array of words that are placed into individual dynamictext fields, which are created in MovieClip objects named word0, word1, word2, and so on.

    The kthMovieClip object has an instance variable scalethat ranges from -k*200 to 300 by

    having 10 added as each frame is entered. When the scale value is between 10 and 300 theword shows on the stage scaled by that value so that the word appears to be movingtoward the front. When scale reaches 300, the MovieClip object is made invisible.

    Enter the following ActionScript code at KeyFrame 1.

    words = "Multimedia,Web,Programming,with,Flash";

    wordList = words.split(",");

    createAllWords(wordList);

    functioncreateAllWords(wordList){

    for(vark=0; k

  • 8/13/2019 Flash8 Lectures

    92/100

  • 8/13/2019 Flash8 Lectures

    93/100

    Flash 8 Lecture Outline Copyright 2008 by Ken Slonneger Page 93

    Example: Form.fla

    This example uses Flash Components to build a form similar to what can be donewith HTML form tags.

    TextInput

    Drag a TextInput Component onto the stage, select it, and give it the instance nameusername.

    Open the Properties Panel (ctrl+F3) and select its Parameters tab.

    Option Default

    editable true

    password false

    text none

    Place a Static text field "Enter Name:" next to the TextInput Component as a label.

    Repeat this process for a password field, except call the instancepasswdand set thepasswordoption to true.

    Retrieving TextInput data:

    trace(username.text);

    trace(passwd.text);

    CheckBox

    Drag three CheckBox Components onto the stage, giving them instance names check1,check2, and check3.

    Open the Parameters tab of the Properties Panel.

    Option Default

    label CheckBox

    labelPlacement right

    selected