Flash 8 Lectures
Flash 8 Lectures
Playing a Movie
Play Enter
Advance one frame .
Move back one frame ,
Create swf file and display movie ctrl+Enter
Publish (create swf and 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, type
a new name, and Enter).
Add a layer
Insert ➜ Timeline ➜ Layer or
Press button on left below layer window
Active 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.
Animation
Three methods
Frame by frame (tedious)
Tweening
Timeline Effects
We can change a movie only on Keyframes.
Tweening
Two kinds: Motion and Shape
Motion Tweening
Can act on Symbol instances, groups, or text instances
Change: position, size, rotation, skew, color, transparency
Creating a Motion Tween
Place two Keyframes on timeline, say frame 1 (already a Keyframe) and frame 30.
Select Keyframe 1 and place Symbol instance or text on stage.
Select Keyframe 30 and place Symbol instance or text on stage.
Create Motion Tween (three methods): Arrow with light blue background
Click on left Keyframe and select Motion from Properties panel Tween menu
Right click anywhere between Keyframes and choose Create Motion Tween
Click anywhere between Keyframes and choose
Insert ➜ Timeline ➜ Create Motion Tween
Examples: Moving Symbols, Rotation word, Skewing symbol, Text moving down and
increasing in size, Symbol changing color and transparency
Note that changes in Symbol instance are made using Transform Tool or the Color
menu in Properties Panel.
Shape Tween
Works with a drawn object, not with a Symbol or text object.
Change a Symbol or text object into a drawing
Modify ➜ Break Apart (ctrl+b)
Once for a single text character
Twice for a text object with multiple characters
Creating a Shape Tween
Place two Keyframes on timeline, say frame 1 (already a Keyframe) and frame 30.
Select Keyframe 1 and create a drawing on stage.
Select Keyframe 30 and create a drawing on stage.
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.
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 Sound
Import a sound file
File ➜ Import ➜ Import to Library (or Scene)
Edit Button Symbol
Put a Keyframe at Down state
Place sound
Example
+ ➜ Web ➜ Go to URL
Enter 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 give
the 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");
}
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 Duplicates
Options
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 Blur
Allow Vertical Blur
Direction of Movement
Example: fire.jpg
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 Offset
Examples: Herky, 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
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 or
component).
Example
Create a Button Symbol.
Give it an instance name, say "xyz".
Select the button instance an open the Actions Panel using
Window ➜ 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.
Gradients
Coloring effect that blends bands of color into each other.
Linear gradients: Straight left-to right, which can be rotated to other
orientations (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).
Timeline Variables
Visible to any script on that particular timeline (all layers).
Creating:
var tName = 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):
var x;
Typed:
var n:Number;
var s:String;
With Initialization:
var y = 123;
var z: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
With typed declarations, ActionScript has static typing so that errors are caught
by the compiler and reported in the Output Panel.
Trace Method
The method trace takes one parameter, converts it to a string, and prints it in
the 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
1. Draw a green disk on the stage and convert it to a Movie Clip Symbol called
GreenBall.
2. Movie Clip Symbols recognize a number of predefined properties such as _x, _y,
_width, and _height. By altering the _x and _y properties, we can cause the Movie
Clip Symbol to move across the stage.
3. Just as Buttons respond to events (press and release), Movie Clips respond to events
such as load, enterFrame, mouseDown, keyDown, among others.
4. In the same way we handle Button events with an on command, we handle Movie
Clip events with an onClipEvent command.
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 edge
speedX = -speedX; // change directions
}
Problem: Ball misses the edge by a little because the _x property is the registration
point of the Movie Clip instance (the plus sign) usually at the center of the object.
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.
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 with
the name "CenterOnStage".
This new command can be very useful.
Filters
Accessed 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.
Blur Filter
This filter blurs the entire content of the instance.
Parameters allow more or less blurring in the x or y direction.
Example
Enter 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.
Example
Enter some large text, say "Flash Filters" with white characters on a black background.
Select the Glow filter.
High Strength, say 380%.
Medium Quality.
Select a green Color.
Select Drop Shadow filter.
Medium Quality.
Distance equal to 7.
Select a yellow Color.
Try different Angle values.
Try some other options.
Knockout: Removes original figure.
Inner Shadow: Puts glow or shadow inside the figure.
Hide Object (Drop Shadow only): Shows only the shadow.
Controls
Strength: Amount of the effect, usually changing the brightness and alpha of the effect.
Quality: Higher quality means better transitions (smoother) and greater aliasing, but also
more computation (slower).
Bevel Filter
This filter gives the instance an embossed look.
This effect is produced by lightening the upper left of the drawing and darkening the
lower right as if there is a light source coming from the upper right.
Options allow a change in the direction of the light source and the colors of the effect.
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, and four. 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 point
bold white font.
one.onRelease = function()
{ keyPressed("1");
}
two.onRelease = function()
{ keyPressed("2");
}
three.onRelease = function()
{ keyPressed("3");
}
four.onRelease = function()
{ keyPressed("4");
}
reset.onRelease = function()
{ keyPressed("reset");
}
function keyPressed(key:String)
{
if (key == "reset")
{
countField.text = "Number of digits: 0";
count = 0;
display.text ="";
return;
}
display.text = display.text + key;
count++;
countField.text = "Number of digits: " + count;
}
The three conversion functions, Number, Boolean, and String, can be applied
to 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 properly
formatted number
"Infinity" Infinity
"-Infinity" -Infinity
"NaN" NaN
Other strings NaN
Array NaN
Object Result from applying
valueOf() to the object
Movieclip NaN
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
class MyClass
{
private var value : Number;
public function MyClass(n : Number)
{ value = n; }
public function perform(m : Number) : Void
{
for (var k:Number = 1; k<=value; k++)
trace(m*k);
}
public function compute() : Number
{ return value*value; }
}
Modifiers public accessible anywhere
private accessible in this class and any subclass
no modifier same accessibility as public
Objects
• Objects are created from a class using the new operator, which invokes a
constructor with matching parameter types.
• These objects may be assigned to variables declared of the type given by the
class name.
• Each object has a copy of every instance variable in its class definition and in
every superclass of that class.
• Instance methods in a class can be called only with an object of the class type
(or a subclass).
• This object is called the receiver of the method and can be referred to by the keyword
this inside of the method.
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 no
parameters 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 extends keyword.
• 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 object
referred to determines which version of the overridden method will be executed. This
property is known as polymorphism or dynamic binding.
• In an instance method, the identifier this refers to the object, the receiver, that is
currently executing the instance method.
• The identifier super can be used to access instance methods (and variables) that have
been overridden (and shadowed) in the subclass.
class Solid
{ // File: Solid.as
private var kind : String;
public function getKind() : String
{ return kind; }
public function volume() : Number // This code is never executed
{ return 0.0; }
}
To make use of Solid and its subclasses, create a Flash document with the following
ActionScript 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.
Execution
Cube volume = 1000
Cube volume = 125
Sphere volume = 418.879020478639
Sphere volume = 268.082573106329
Cone volume = 47.1238898038469
Cone volume = 134.041286553164
Abstract Classes
• ActionScript does not allow abstract classes.
• Interfaces must be used instead.
interface Printable
{ // File: Printable.as
function printNum(n : Number) : Void;
}
To make use of Printable and its implementations, create a Flash document with the
following ActionScript code at its first Keyframe. It file must be in the same directory as
Printable.as, FirstImpl.as, and SecondImpl.as, and must be saved before it is tested.
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 instantiated
when 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:
class GreenBall extends MovieClip
{ }
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;
}
The decision making for bouncing off of the edges of the stage is encapsulated
in an instance method checkBounds for the object named green.
Actually, the _root object is redundant, which onEnterFrame responds to the main
timeline 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 <= 0) // left edge
{
green._x = 0 + green._width/2;
green.dx = -green.dx;
}
if (green._y + green._height/2 >= Stage.height) // bottom edge
{
green._y = Stage.height - green._height/2;
green.dy = -green.dy;
}
else if (green._y - green._height/2 <= 0) // top edge
{
green._y = 0 + green._height/2;
green.dy = -green.dy;
}
}
Add Start and Stop buttons (Symbols) to the stage with instance names myStart
and myStop.
Place the following code on Keyframe 1 with the code that is already there.
myStop.onPress = function()
{
green.saveX = green.dx;
green.saveY = green.dy;
green.dx = green.dy = 0;
}
We have added four instance variables (dx, dy, saveX, saveY) to the object named green,
which also has access to instance variables (_x, _y, _width, _height, among others) inherited
from 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 square and the object green overlap,
square.hitTest(green) returns true.
Add an instance method:
green.checkHit = function()
{
if (square.hitTest(green))
{
green.dx = - green.dx;
green.dy = - green.dy;
}
}
Solution: Test whether the ball is within |dx| distance of the left or right side of
the 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 checkHit instance methods follows.
Changes to GreenBall.fla
onLoad = function()
{
green.dx = 8;
green.dy = 4;
bonk = new Sound();
bonk.attachSound("bonk.wav");
}
green.checkHit = function()
{
if (square.hitTest(green))
{
bonk.start();
// Rest of the method is the same.
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);
}
Example: Drawing.fla
Increase the Frame rate to 24 to reduce flicker.
The MovieClip properties, xmouse and ymouse, hold the current position of the mouse.
Without an object specification, we get _root, the main timeline Movie Clip.
In a new Flash document, enter the following code at Keyframe 1.
onMouseDown = function()
{
lineStyle(4, 0x0000ff, 100);
moveTo(_xmouse, _ymouse);
}
onMouseUp = function()
{
lineStyle(0, 0x000000, 0);
}
onMouseMove = function()
{
lineTo(_xmouse, _ymouse);
}
onMouseDown = function()
{
if (Key.isDown(Key.SHIFT))
{
clear();
}
else
{
lineStyle(4, 0x0000ff, 100);
moveTo(_xmouse, _ymouse);
}
}
Mouse Class
Two class methods in Mouse make the mouse cursor disappear and reappear.
Mouse.hide();
Mouse.show();
Example: NewCursor.fla
Draw a small graphic, say a three-pointed start, on the stage and convert it to a Movie Clip
Symbol.
Give the instance on the stage the name pointer.
Increase the Frame rate to 24.
Enter the following code at Keyframe 1.
Mouse.hide();
onEnterFrame = function()
{
pointer._x = _xmouse;
pointer._y = _ymouse;
}
Example: MyEvents.fla
Place a blue rectangle MovieClip instance on the center of the stage and call it box.
To get the box object 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'); }
Example: KeyPresses.fla
onEnterFrame = function()
{
if (Key.isDown(65))
{
trace("Letter 'a' pressed");
}
else if (Key.isDown(Key.SPACE))
{
trace("Space pressed");
}
else if (Key.isDown(Key.UP))
{
trace("Up arrow pressed");
}
}
Array Creation
var a : Array = new Array(); // an empty array
b = new Array(4); // an array with 4 undefined values
c = [1, 2, 3, 4, 5]; // an array literal
d = ["abc", 2+2, Math.PI, 'xyz']; // arrays can be nonhomogeneous
e = new Array(["a", "b", "c"]);
f = [[1,2,3],[4,5,6]]; // a two dimensional array
g = new Array(['A','B'], ['Y','Z']); // a two dimensional array
Regular Expressions
x* Zero or more copies of the item x.
x+ One or more copies of the item x.
x? One copy of x or none at all.
pop() : Object Removes the last element from this array and
returns the value of that element.
shift() : Object Removes the first element from this array and
returns the value of that element.
Queue Behavior
Use push and 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
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 slice and splice operations did not always work correctly for me
when applied to the array resulting from an application of concat.
Vector Motion
An object moving on the stage has speed and direction, which are represented by the
concept of a vector.
A vector can be viewed as an arrow whose angle gives the direction and whose length
represents the speed.
Problem: Translate a vector into the dx, dy values that are used to specify motion in Flash.
Conversion
180° is equivalent to π radians
degrees/180 = radians/ π
radians = π • degrees / 180
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, which
is the positive remainder on dividing by 360.
Note: The sine and cosine functions don't care about the magnitude of the angle; they
work just as well with negative angles and angles above 360°.
Problem: The remainder operator (%) in ActionScript does not compute the modulo
function correctly.
Example: Divide by 4
n n%4 mod(n, 4)
5 1 1
4 0 0
3 3 3
2 2 2
1 1 1
0 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.
function mod(num, div)
{
r = num % div;
return r<0 ? r+div : r;
}
car.speed = 0;
car.direction = 45; // degrees
car.maxSpeed = 15;
onEnterFrame = function()
{
checkKeys();
turn(car);
move(car);
}
function checkKeys()
{
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);
}
}
When a class has the dynamic modifier, properties may be added to its objects
outside of its class definition.
Recommendation: Dynamic classes are considered poor OOP design, although this
usage is found in Flash code frequently. A better approach would be to use a subclass
of the class to add a property.
Visibility Modifiers
public and private
No modifier on a member of a class means that it is public.
ActionScript does not allow final as a modifier.
Viewing Properties
Change the Box class to read as follows.
dynamic class Box
{
var width : Number = 25;
var height : Number = 50;
var description : String = "red box";
}
Consider this ActionScript code in a Flash document.
b = new Box();
trace(b.width); // prints 25
trace(b.height): // prints 50
Contrast Syntax
With the syntax b.width and 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 dynamic
properties belong to this new object only.
var ob : Object = {x:33, y:44, color:"blue", visible:false};
Output
-----------------------------------------
Property name: x
Property value: 33
-----------------------------------------
Property name: y
Property value: 44
-----------------------------------------
Property name: color
Property value: blue
-----------------------------------------
Property name: visible
Property value: false
-----------------------------------------
Removing a MovieClip
Global class method
removeMovieClip(instanceName);
MovieClip instance method
instanceName.removeMovieClip():
Example: MakeBalls.fla
Create a MovieClip Symbol called Ball (a green disk).
Create a Button Symbol and place an instance of it on the stage with the label "Make a Ball"
and with instance name theButton.
Place a dynamic text field on the stage with instance name display.
Enter the following ActionScript code at KeyFrame 1.
k = 0;
theButton.onRelease = function()
{
k++;
_root.attachMovie("Ball", "ball"+k, 10*k);
currentBall = eval("ball"+k);
w = currentBall._width;
h = currentBall._height;
currentBall._x = Math.random()*(Stage.width-w)+w/2;
currentBall._y = Math.random()*(Stage.height-h)+h/2;
currentBall.index = k;
function start()
{
dx = xspeed;
dy = yspeed;
}
function checkBounds()
{
if (_x + _width/2 >= Stage.width)
{ dx = -dx; }
if (_x - _width/2 <= 0)
{ dx = -dx; }
if (_y + _height/2 >= Stage.height)
{ dy = -dy; }
if (_y - _height/2 <= 0)
{ dy = -dy; }
}
function onRelease()
{
if (Key.isDown(Key.SPACE))
{ removeMovieClip(this); }
else if (Key.isDown(Key.UP))
{ start(); }
else if (Key.isDown(Key.DOWN))
{ stop(); }
}
}
Using Ball.as
Create a Flash document ManyBall.fla with following code at KeyFrame 1.
for (k = 0; k< 50; k++)
{
attachMovie("Ball", "ball" +k, k + 10);
}
Relationships
position = velocity • time + initialPosition
velocity = acceleration • time + initialVelocity
Consider two points in time, t1 and 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 the
name ball.
Enter the following ActionScript code at KeyFrame 1.
ball.dx = 10;
ball.dy = 5;
gravity = 3;
Notes
• This program is similar to previous bouncing ball programs, but with two
modifications to make it more realistic.
• When the ball bounces off a surface, its reversed speed is only 90% of the impact
speed to model the fact that balls lose speed when they bounce.
• With each passing frame, the velocity in the y direction (dy) is modified by adding
the gravity constant to model the decreasing velocity when the ball is rising and
the increasing velocity when the ball is descending.
• The actual value of the gravity constant cannot be determined physically since we
are modeling the world in Flash. Try different values for the constant until the
simulation looks good.
function turn(mc)
{
degrees = mc.direction -90;
radians = degrees / 180 * Math.PI;
mc.dx = mc.speed*Math.cos(radians);
mc.dy = mc.speed*Math.sin(radians);
}
function move(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 stage
mc._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 key
is 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 top
of the stage and then returns if it has not met one of the edges.
With a frameDelay value of 12 and the Frame Rate set to 12 frames per second, the word
displayed changes every second.
Note that the variable wordNum cycles through the values 0, 1, 2, 3, 4, 5 repeatedly, and
the variable frameCount cycles through the values 12, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 repeatedly.
Both of these cycles can be calculated using the modulo operator, as shown below.
onLoad = function()
{
sentence = "Imagination is more important than knowledge";
wordList = sentence.split(" ");
wordNum = 0;
frameDelay = 12;
frameCount = 0;
}
onEnterFrame = function()
{
if (frameCount % frameDelay == 0)
{
display.text = wordList[wordNum];
wordNum = (wordNum+1) % wordList.length;
}
frameCount++;
}
MovieClip Methods
createEmptyMovieClip(instanceName : String, depth : Number) : MovieClip
This method creates an empty MovieClip object as a child of an existing MovieClip,
the receiver of the method, giving it the name instanceName.
It returns the new MovieClip whose registration point is in its upper-left corner.
Drawing Methods
Some of these methods have been described earlier.
lineStyle(thickness : Number, rgb : Number, alpha : Number) : Void
moveTo(x : Number, y : Number) : Void
lineTo(x : Number, y : Number) : Void
endFill() : Void
This method marks the end of the drawing of the shape to be filled.
Example: Fill.fla
Enter the following ActionScript code at KeyFrame 1.
createEmptyMovieClip("mc", 10);
mc.lineStyle(4, 0x000000, 100);
mc.beginFill(0xff6600);
mc.moveTo(50, 50);
mc.lineTo(150, 50);
mc.lineTo(150, 200);
mc.lineTo(50, 200);
mc.endFill();
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;
}
}
Example: Snowflakes.fla
Set the background of the stage to a deep blue.
Enter the following ActionScript code at KeyFrame 1.
numSnowflakes = 50;
for (var k=0; k<numSnowflakes; k++)
{
mc = createSnowflake(k);
with (mc)
{
_x = Math.random()*Stage.width; // 0 to Stage.width
_y = Math.random()*Stage.height; // 0 to Stage.height
mc.speed = Math.random()*2 + 4; // 2 to 6
mc.drift = Math.random()*3 - 1.5; // -1.5 to 1.5
mc.rotate = Math.random()*18 - 9; // -9 to 9
}
}
onEnterFrame = function()
{
moveSnowflakes();
}
Observe that when the instance variables speed, drift, and rotate are first introduced in
the first with command, they must be fully qualified with the identifier mc to bring
them into existence.
Note: There are two global functions for duplicating a MovieClip object, which should
not be confused with this instance method.
Example: Duplicate.fla
Enter the following ActionScript code at KeyFrame 1.
createEmptyMovieClip("box", 0);
var w : Number = 400;
var h : 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);
Loading Data
Create a text file composed of name-value pairs delimited by ampersands (&).
The data should be URL-encoded (spaces replaced by + and many symbols represented
by their hexadecimal values in the form %2B).
Example: LoadVars.fla
Place two buttons on the stage with the labels LOADVARS and SHOWVARS and
the instance names load and show.
Enter the following ActionScript code at KeyFrame 1.
var ready = false;
load.onRelease = function()
{
lv = new LoadVars();
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);
}
else trace("Variables not loaded yet.");
}
The load is "successful" even if the data file has an incorrect file. It is unsuccessful only
if the file is missing.
Output When LOADVARS Button Pressed and File Does Not Exist
Load Complete: false
Error opening URL "file:///Cornfed/Users/slonnegr/Desktop/CurrentFlash/data"
Sending Data
Server programs expect data to be sent to them as name-value pairs separated by
ampersands.
For a GET request the parameter pairs go at the end of the URL.
For a POST request that parameters go in the body of the request.
When the request is sent to a Java server program running at port 8888 on the computer
r-lnx233.cs.uiowa.edu, the result is the following web page.
Shared Objects
Flash has a mechanism that allows an executing Flash movie to store and/or retrieve
limited 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 typed
by 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 method
getLocal.
var so : SharedObject = SharedObject.getLocal("foobar");
or
var so : SharedObject = SharedObject.getLocal("foobar", "/");
In the first version, the information stored can be accessed only by the same executing
Flash movie.
The information to be stored and retrieved is accessed through an instance variable data
belonging to the SharedObject object.
Example
Create a Flash document SharedObjectSave.fla with the following code at KeyFrame 1.
var so:SharedObject = SharedObject.getLocal("foobar","/");
so.data.nums = new Array(121, 143, 165, 187);
so.data.isHungry = false;
so.data.userName = "Claude";
so.data.ob = { x:33, y:55, z:77};
so.flush();
The flush command forces the values to be saved locally, but closing the swf file will have
the same effect.
Output
121,143,165,187
false
Claude
33
55
77
Observe that information is stored in the local file using name-value pairs similar
to attributes for the property data of the SharedObject object.
Example: SharedObjectLogin.fla
Create two input text fields with the instance names myLogin and myPasswd and label
them appropriately.
Create four button with instance names saveButton, loadButton, clearButton, and
resetButton and with labels "Save", "Load", "Clear", and "Reset", respectively.
Enter the following ActionScript code at KeyFrame 1.
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 the
other text field. It makes use of the Selection class.
These values my be altered by creating a new TextFormat object, defining values for
some 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. It’s too crowded.";
myFmt = new TextFormat();
myFmt.size = 24;
myFmt.color = 0x00ffff; // cyan
myFmt.bold = true;
myTF.setTextFormat(myFmt);
function createAllWords(wordList)
{
for (var k=0; k<wordList.length; k++)
{
mc = createWord(k, wordList[k]); // create movie clip with this word
mc._x = Math.random()*(Stage.width-300)+150;
mc._y = Math.random()*(Stage.height-100)+50;
mc._xscale = mc._yscale = 0;
mc.scale = 0-k*200; // set scale variable to a nonpositive amount
}
}
function moveWords()
{
for (var k=0; k<wordList.length; k++)
{
mc = this["word"+k];
mc.scale = mc.scale + 10; // increase scale of this movie clip
if (mc.scale > 300)
{ // hide movie clip when scale is too big
mc._visible = false;
}
else if (mc.scale > 0)
{ // set scale of movie clip to scale when positive
mc._xscale = mc.scale;
mc._yscale = mc.scale;
}
}
}
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 false
Enter labels Apple, Banana, and Peach for the three CheckBox Components.
Retrieving the checked values:
fruit = new Array();
for (k=1; k<=3; k++)
{
ch = eval("check"+k);
if (ch.selected)
{
fruit.push(ch.label);
}
}
trace(fruit);
List
Drag a List Component onto the stage, giving it the instance name city.
Open the Parameters tab of the Properties Panel.
Option Default
data []
labels []
multipleSelection false
rowHeight 20
Change multipleSelection to true.
Double click on the labels value ([]) and enter these value (using the + button).
Berlin
Chicago
Dublin
London
New York
Paris
Rome
Vienna Click OK.
TextArea
Drag a TextArea Component onto the stage, giving it the instance name message.
Change its width to 200 and its height to 80.
Open the Parameters tab of the Properties Panel.
Option Default
editable true
html false
text none
wordWrap true
Change the value of text to "Message contents.".
Place a Static text field above the TextArea with the label "Please leave your message here.".
Retrieving TextArea data:
trace(message.text);
Button
Drag two Button Components onto the stage, giving them the instance names submit
and reset.
Open the Parameters tab of the Properties Panel.
Option Default
icon none
label Button
labelPlacement right
selected false
toggle false
reset.onRelease = function()
{
resetForm();
}
function resetForm()
{
username.text = "Claude";
passwd.text = "catcatcat";
blue.selected = true;
check1.selected = false;
check2.selected = false;
check3.selected = true;
area.text = " Message contents.";
Call the resetForm method when the Flash document is first loaded to initialize
the Components on the stage.
Example
Open the web site called Flash Exchange: Select Help ➜ Flash Exchange.
Choose Flash under Exchange By Product.
Choose Freeware as the License type and click Filter.
Scroll down to an item called Dice and click Download.
Sign in to your Adobe account (or create one).
You will find a file DiceComp4.mxp that has been downloaded.
Install the new Component.
Select Help ➜ Manage Extensions....
Click the Install icon in the Extension Manager window.
Navigate to the file DiceConmp4.mxp and click Install or Open.
Example: Components.fla
This Flash document illustrates using several more of the Flash Components and
using the new Dice Component that we just installed.
ComboBox
Drag a ComboBox Component onto the stage, giving it the instance name myCombo.
Open the Parameters tab of the Properties Panel.
Option Default
data []
editable false
labels []
rowCount 5
The ComboBox may be populated the same way as the List Component.
As an alternative, both ComboBox and List can be populated dynamically.
myCombo.removeAll();
myCombo.addItem("Macromedia", "http://www.macromedia.com");
myCombo.addItem("Adobe", "http://www.adobe.com");
myCombo.addItem("Apple", "http://www.apple.com");
myCombo.addEventListener("change", doChange);
function doChange(evt)
{ getURL(evt.target.selectedItem.data);
NumberStepper
Drag a NumberStepper Component onto the stage, giving it the instance name num.
Open the Parameters tab of the Properties Panel.
Option Default
maximum 10
minimum 0
stepSize 1
value 0
Change maximum to 100, minimum to 2, stepSize to 2, and value to 50.
Dice
Drag a Dice Component onto the stage, giving it the instance name die.
Open the Parameters tab of the Properties Panel.
Option Default
colArr []
cornerColor 0xA9A9A9
dotColor 0x333333
DiceNum 3
IsJumping true
Drag a Button Component onto the stage, giving it the instance name submit and
the label Submit. Enter the following ActionScript code to respond to the button.
submit.onRelease = function()
{
trace("ComboBox:" + myCombo.value);
trace("Date: " + date.selectedDate);
trace("Number: " + num.value);
trace("Die: " + die.DiceNum);
}
Example: SendForm.fla
This Flash document produces the same form used in Form.fla, but when the submit
button is pressed, the data is collected into a LoadVars object and sent to a Java Servlet
that displays all the parameters and values in a web page.
Enter the following ActionScript code at KeyFrame 1.
submit.onRelease = function()
{
send = new LoadVars();
send.username = username.text;
send.passwd = passwd.text;
send.color = color.selectedData;
cities = city.selectedItems;
cityCodes = new Array();
for (k=0; k<cities.length; k++)
{
cityCodes.push(cities[k].data);
}
send.city = cityCodes;
send.message = area.text;
send.send("http://webdev.divms.uiowa.edu/slonnegr-tomcat4/ShowParams",
"_self", "GET");
}