Course notes
syllabus | schedule | topics | projects | class notes | resources | students | ARTC courses
 Lectures:
Lecture A: The Flash Interface Lecture 4: User Input
Lecture B: Animation Lecture 5: Extras & Game Design
Lecture 1: Drawing with Code and ActionScripting Lecture 6: Linking up the Nucleus
Lecture 2: Graphics Application Development Lecture 7: Brainstorming Game Types
Lecture 3: Working with Movieclips Lecture 8: Topics for Discussion
  Lecture 9: Preloaders and JavaScript Windows
 
Notes: [Publishing]    [External]    [Interface]    [Drawing]    [Fills]    [Curves]    [Variables]    [Functions]    [Loops]    [Randomness]    [Buttons]    [Listeners]    [Text]   

 Lecture 1: Publishing and Using the Drawing API in ActionScripting
 

PREPARING FLASH MOVIES FOR THE WEB:

Higher Quality = Larger File = Longer Download time = Slower Movie, (smoother anim, better sound)
What makes a file BIG? - lots of bitmaps, sounds, video clips, frame by frame animation instead of tweened animations, many animations at once, embedded fonts, gradients, drawn elements instead of symbols & groups.
To Use the Bandwidth Profiler:  Simulates Streaming to test Size and Bandwidth Profiling.

  1. Open the Flash file
  2. Control > Test Movie.  Flash opens the movie in Flash Player
  3. From the View menu, choose the Download Settings you want to test.
  4. Choose View > Bandwidth Profiler, Flash graphs the amount of data that is being transmitted through the timeline.  The bars represent #of bytes per frame. The bottom line represents the amount of data that will safely download fast enough to keep up with the movie's frame rate.  Any frame with TOO MUCH DATA will force the movie to pause at that frame.

Also can use the : View > Frame by Frame Graph=single frame (data per);  OR Streaming Graph=shows download time


PUBLISHING AND EXPORTING:

You can create the .swf and .html file for the web, as well as gif, jpg, png, QuickTime and RealPlayer.
To set the Publishing Format:

  1. Open the Flash file you're ready to publish
  2. File > Publish Settings (OPT-Shift-F12). The Publish Settings dialog box appears.
  3. Click Formats Tab.
  4. Choose HTML and enter the filename.  (the Flash option is automatically select also).
  5. To set options for those formats, click on the top menu.
  6. Click OK. Flash saves the settings with your file.

** Changing the Publish Settings will also change the preview when you Test Movie!

To Publish the movie:

  1. Open the movie
  2. File > Publish  (or click Publish in the Publish Settings window right after you set them above)

Flash Player Options:

Version:  Choose 9 so it does not require Flash Player 10 to play (although we have version 10).
Load Order:  Top Down / Bottom Up;  order of layers drawn in first frame of your movie
ActionScript version: pick 3.0
Generate Size Report:  Check this to create a text file with data download info (your use only)
X Protect from Import: Prevents viewers from your .swf file and converting it back to a Flash movie.
Omit Trace Actions: strips trace actions; reduces file size slightly
_   Permit Debugging: Allows you (& others) to debug .swf file
Compress Movie: use for text-heavy movie
Export hidden layers: Even if you hide them, they will reappear in the published version
JPEG Quality:  Sets compression for any bitmaps in your movie (0 is lowest quality, smallest file)

Audio Stream/ Audio Event:  Set compression parameters:  (llkHz is web standard)

  1. For short event sounds, choose ADPCM (2-bit is worst sound, 5-bit is best)
  2. For longer streaming sound, choose MP3 (20kbps+ = stereo; Fast for web playback)

 Override sound settings: √ this if you've adjusted each sound file individually (preserve sound quality).

HTML Options:

Template: 
- Flash Only (Default);  Simplest, but no Alt tags to warn if viewer doesn't have Flash 6 Player

- Detect Flash Version:  This uses JavaScript to check if Flash 6 plug-in is installed.

Dimensions: (adjust movie display window (created by OBJECT EMBED tags)
- Match Movie:  Exact measurements you specified in Document Properties box.
- Percent: % of browser window (what holds the entire web page)
- Pixels:  Enter new values for new window size

Playback:

  1. Paused at Start:  makes user begin movie themselves
  2. Display Menu:  Creates the menu with the above playback options.
  3. Loop:  loops movie
  4. Device Font:  speeds playback on Windows (substitutes aliased system fonts with user's system; only in static text blocks with enabled device fonts)

Quality:

  1. Low:  Flash Keeps antialiasing OFF
  2. AutoLow:  Flash starts with antialiasing off, but tests viewer's computer can handle it, turns it on.
  3. Autohigh:  Flash starts with AA on, but turns it off if frame rate drops
  4. Medium:  takes middle ground - forgoes bitmap smoothing, but does some antialiasing
  5. High:  uses antialiasing on everything but animations with bitmaps
  6. Best:  Antialiasing is always on.

Window Mode: (effects Windows in IE 4 or later only); supports transparent backgrounds.

  1. Window: plays the movie in its own window within the web page
  2. Opaque Windowless:  Makes transparent areas block out other elements on web page
  3. Transparent Windowless:  Allows elements under movie to show through

Scale: (Use only when you define a movie-display window different from original Flash movie)
- Default (show all):  Keeps movie's original aspect ratio, but resizes to fit completely in chosen size (may  cause gaps at top/bottom or sides)
- No Border:  keeps original aspect ratio, and resizes so new rectangle is filled with movie   
   (some of the movie edges may be cropped).
- Exact Fit: Changes movie's height / width to fit, but may change aspect ration & distort image
- No Scale:  keeps movie at a constant size (resizing browser window can crop image)
* Set to 95% to eliminate scroll bar.  At 100%, the scroll bar always appears.

Flash Alignment: (alignment of movie window within movie-display window (created by HTML)
- Horizontal:  Left, Center, Right                                   
- Vertical:  Top, Center, Bottom

Show Warning Message:  displays error messages when it finds problems with  your html tags.

You will want to test which settings are best for your specific movie. 
Create multiple versions so that you may see which one is best.

There are many ways of programming in ActionScript. We will create external files that read by the Flash file.

Step 1: File - New ActionScript File (NOT Flash File)
Step 2: Save As... and name it a name with NO spaces in the filename

package {
	import flash.display.*;
	import flash.text.*;
	
	public class Exercise1 extends MovieClip {
		
		public function Exercise1 () {
			//do something here
		}
		
	}
}
EXPLANATION

A PACKAGE contains CLASSes. These hold the code necessary to trigger events and perform the operations you desire.

You need to import the libraries you will be using for your project. The display library holds the graphics functions (methods) and properties. The text library enables you to work with text methods and properties.

You need to make your class public so it can be see by outside sources.

When you say that a class extends something (in this case a MovieClip) then it means that all the functionality of the original object is still intact and you are adding more functionality. The MovieClip in this case is the Stage (stageshave timelines just like MovieClips so the stage is essentially a MovieClip)

Name your class and your first function the same name as the ActionScript file and this is called a Constructor Function and it will execute immediately without having to be called.

ActionScript is CASE sensitive - ALWAYS pay attention to your coding.

// is how you write comments in your code - ALWAYS comment your code.

CONNECTING YOUR CODE TO FLASH

File - New - Flash File (ActionScript 3.0)
Save As... name it and save in the same place as your ActionScript file (you can name it the same as the ActionScript file)

Open the Properties Panel and anter the Document Class name: (same as the ActionScript file name)

class

Use the TABS on the top to jump between ActionScript and Flash files.

Test to see if it works by adding this to your public function code:

trace("Yeah, it works!");

Go to the Flash Movie and Control - Test Movie (make sure all files are saved before Testing)

Icons on the top:

code window

  1. Add new item to the script
  2. Find
  3. Check Syntax
  4. Auto Format
  5. Code Code Hint
  6. Debug Options
  7. Collapse between braces
  8. Collapse selection
  9. Expand All
  10. Apply block comment
  11. Apply line comment
  12. Remove comment
  13. Show/Hide Toolbox

Flash is limited in what it provides you so you need to create more complex shapes from simple elements such as lines and curves.

The Basic Flash Drawing Tools:

lineStyle()
moveTo()
lineTo()
curveTo()                           
beginFill()
endFill()
drawRect()
drawRoundRect()
drawCircle()
beginGradientFill()
clear() 

General Rules for lines:
You must set the lineStyle() prior to drawing a line.

Lines always start drawing from where the last one left off unless you use a moveTo() before drawing your line.

First time drawing a line, it will start at 0,0 unless you use a moveTo()


Method Properties:

lineStyle(lineWidth, color, alpha)
     lineWidth is a Number
     color is defined using hexidecimal like so: 0xFFDD66
     alpha is a Number 0.0 to 1.0

moveTo(x, y)
     x is a Number - horizontal
     y is a Number - vertical

lineTo(x, y)
      x is a Number - horizontal
      y is a Number - vertical

Typically you would use the following order when writing code:

    this.graphics.lineStyle(2, 0x000000, .2);
this.graphics.moveTo(100,100);
this.graphics.lineTo(200,200);

DO IT: Add the above code to your Constructor Function


Rectangle code:

this.graphics.drawRect(0, 0, 100, 80);

drawRect(x1, y1, s1, s2)
     x1 is the top left X
     y1 is the top left Y
     s1 rect size horizontal
     s2 rect size vertical

Rounded Rectangle code:

this.graphics.drawRoundRect(0, 0, 100, 80, 15, 15);

drawRoundRect(x1, y1, x2, y2, Ew, Eh)
     Ew is the ellipse width - the corner curve - measured in degrees
     Eh is the ellipse height - the corner curve - measured in degrees

Fill code:

 this.graphics.beginFill(0xFF0000);
 this.graphics.drawRect(0, 0, 100, 80);
 this.graphics.endFill(); 

beginFill(color)
     color is defined using hexidecimal like so: 0xFFDD66
     always set the fill before you make the rectangle

endFill()
     always end the fill because that is when ActionScript actually draws the fill on the screen


Gradient Fill code:

// import this library to use gradient color transformations
 import flash.geom.*

 var matr:Matrix = new Matrix();
matr.createGradientBox(200, 200, Math.PI/3, 0, 0);
this.graphics.beginGradientFill(GradientType.LINEAR, [0x000000,0xffffff], [1,1], [0,255], matr, SpreadMethod.PAD, InterpolationMethod.LINEAR_RGB, 0);
this.graphics.drawRect(100,100, 100, 80);
this.graphics.endFill();

beginGradientFill(type:String, colors:Array, alphas:Array, ratios:Array, matrix:Matrix = null, spreadMethod:String = "pad", interpolationMethod:String = "rgb", focalPointRatio:Number = 0):void

type: GradientType.LINEAR or GradientType.RADIAL

colors: An array of RGB hexadecimal color values to be used in the gradient; for example, red is 0xFF0000, blue is 0x0000FF, and so on. You can specify up to 15 colors. For each color, be sure you specify a corresponding value in the alphas and ratios parameters.

alphas: An array of alpha values for the corresponding colors in the colors array; valid values are 0 to 1.

ratios: An array of color distribution positions; valid values are 0 to 255. The value 0 represents the left-hand position in the gradient box, and 255 represents the right-hand position in the gradient bo x.

matrix: a boxed area that you can define for where the gradient is positioned on the screen. Create a new matrix and set the:

Gradient box width: the width (in pixels) to which the gradient will spread
Gradient box height: the height (in pixels) to which the gradient will spread
Gradient box rotation: the rotation (in radians) that will be applied to the gradient
       EX: Math.PI/4; = 45 degrees, Math.PI/2; = 90 degrees.

gradients

Horizontal translation: how far (in pixels) the gradient is shifted horizontally
Vertical translation: how far (in pixels) the gradient is shifted vertically

spreadMethod: String (default = "pad") : SpreadMethod.PAD, SpreadMethod.REFLECT, or SpreadMethod.REPEAT.


interpolationMethod: String (default = "rgb") : InterpolationMethod.LINEAR_RGB or InterpolationMethod.RGB

focalPointRatio: Number (default = 0) — A number that controls the location of the focal point of the gradient. 0 means that the focal point is in the center. 1 means that the focal point is at one border of the gradient circle. -1 means that the focal point is at the other border of the gradient circle. A value less than -1 or greater than 1 is rounded to -1 or 1.

endFill()
     always end the fill or it will effect the elements you draw afterwards

Sample code:

 var fillType:String = GradientType.LINEAR;
 var colors:Array = [0xFF0000, 0x0000FF];
 var alphas:Array = [1, 1];
 var ratios:Array = [0x00, 0xFF];
 var matr:Matrix = new Matrix();
 matr.createGradientBox(200, 200, 0, 0, 0);
 var spreadMethod:String = SpreadMethod.PAD;
this.graphics.beginGradientFill(fillType, colors, alphas, ratios, matr, spreadMethod); this.graphics.drawRect(0,200,100,100); this.graphics.endFill();

More information on gradient fills:
Greating Gradient Lines and Fills
ActionsScript 3.0 Graphics


Circle code:

drawCircle(x1, y1, radius)

var matr:Matrix = new Matrix();
matr.createGradientBox(200, 200, Math.PI/-1.5, 0, 0);
this.graphics.beginGradientFill(GradientType.RADIAL, [0xffffff,0x000000], 
            [1,1], [0,255], matr, SpreadMethod.PAD, InterpolationMethod.LINEAR_RGB, .5);
this.graphics.drawCircle(100, 100, 80);
this.graphics.endFill(); 


Draws an ellipse:

drawEllipse(x1, y1, width, height)

 this.graphics.lineStyle(5, 0x000000, 1);
 this.graphics.beginFill(0x00FF00);
 this.graphics.drawEllipse(200, 100, 300, 80);
 this.graphics.endFill(); 

Clear code:

this.graphics.clear();

Use this to clear the screen.

Curves are Bezier curves - they have handles (anchors) to control the curvature
The curve is like a line in that it starts where the last line left off so you may need a moveTo before drawing your your curve.

CurveTo(controlPointX, ControlPointY, x, y)

controlPointX:Number - specifies the horizontal position of the control point - this determines the curvature of the line.
controlPointY:Number - specifies the vertical position of the control point - this determines the curvature of the line.
x:Number - An number that specifies the end point X.
y:Number - An number that specifies the end point Y.

Example:
this.graphics.curveTo(0,200,100,200);
this.graphics.curveTo(200,200,200,100);
curveTo

How to get coordinates
Go to Flash and draw or import the image you want to draw using code
Go to the Windows menu and turn on the Info panel
Position your cursor over the points and write down the coordinates or the points you want


Other graphic methods: Go to the Adobe Reference site

Defining Variables:

Define then assign a value:

var myVariable:Number;
myVariable = 5;

Define and assign a value in one line:

var myVariable:Number = 5;

Always define the type of the information a variable will hold.
It can hold any of these types (plus more):

Number
String
Boolean
int
- integer
uint
- positive integers only

Defining the Function:

Functions are used when you want to organize lines of code into logical chunks and when you want to reuse code over and over

Actionscript has built in functions and you can also make your own. The basic structure is as follows:

public function nameOfFunction():void {

}

Access Modifiers:

public means that the function is accessable from any class.
private means it cannot be accessed from outside the class that defines it.

NAME of FUNCTION: The name of the function starts with a lower letter and cannot have spaces in the name

void - means this function does not return any information. A function can return a number of different types of data:

Number
String
Boolean
int
uint

Always enclose the function in { }

Calling the Function:

You put the call to the function anywhere in your code

nameOfFunction();

Passing information into a function:

You can pass any type of information into a function to be used.

Ex 1:
myFunction(5);

EX2:
var myAge:Number = 20;
myFunction(myAge);

public function myFunction(theInfo:Number): void {
      trace(theInfo);
}

A function that returns information

When you want to get information back from a function, you need to replace the VOID that used with the past examples of functions with the type of information that you want to get back.

//calling the function
public function doit() {
    trace(increaseSize(10));
}

//the function that returns a value
public function increaseSize(theSize:Number):Number {  
     var biggerSize:Number;
     biggerSize = theSize + 5;
     return biggerSize;
}

Sample function code:

package {
	import flash.display.*;
	public class Exercise1 extends MovieClip {

		public function Exercise1() {
			var myAge:Number=20;
			myFunction(myAge);
		}

		public function myFunction(theInfo:Number): void {
		      trace(theInfo);
		}
	}
}

 

For loops are used when you know how many times you have to go through the loop

var i:Number;
       for (i = 0; i < 5; i++) {
       trace(i);
} 


Seeing a For Next loop in action (with a function)

package {
   import flash.display.*;

   public class Exercise1 extends MovieClip {
	
		public function Exercise1() {
           //call the function and pass it the number of times you want it to make a cube
			makerow(6);
		}

		//NumCubes is the number of cubes it will make in a row
		public function makerow(NumCubes:Number):void {
			//offset is the amount of space between the cubes
			var offset:Number=100;
			//pos is the position of the cube 
			var pos:Number = 0;
			//i is the counter variable
			var i:Number;
			//start the fill
			this.graphics.beginFill(0xFF0000);
			//go through the loop
			for (i = 0; i < NumCubes; i++) {
				this.graphics.drawRect(pos, 0, 50, 50);
				//add the offset to the position each time through the loop
				pos=pos+offset;
				//just test to see what numbers you are getting
				trace(pos);
			}
			//turn off the fill
			this.graphics.endFill();
		}
	 }
}

While loops can go through the loop a variety of times but DO NOT forget to alter the loop variable inside the loop or you will have an infinite loop. Hit ESC if this happens.

var i:Number = 0;
while (i < 5) {
       trace(i);
        i++;
}

The above code will start at 0 and go until the variable hits 4 then it goes through one last time. It increments the variable by one each time.

Sample code example:

package {
	import flash.display.*;

	public class Exercise1 extends MovieClip {

		public function Exercise1() {
			var i:Number=0;
			var offset:Number=100;
			while (i < 6) {
                    //call the function to draw the rect and circle
				drawThing(i*offset);
				i++;
			}
			
		}
		public function drawThing(clipPos:Number):void {
			//create a rectangle 
			this.graphics.beginFill(0x0000FF);
			this.graphics.drawRect(clipPos, 100, 50, 50);
			this.graphics.endFill();
			   //create a circle 
			this.graphics.beginFill(0xFFFF00);
			this.graphics.drawCircle(clipPos,100,20);
			this.graphics.endFill();
		}
	}
}

Random is a method of the Math class. A class is a definition of methods and properties and variables that are grouped together.

Math.random() returns a number between 0 and 1 (not including 1), so it could return .99999. We have to multiply it to get usuable numbers typically.

Math.random() * 50; will give you a number from 0 to 49.99999999.

If you want to get rid of the excess numbers after the decimal point, you need to use Math.Floor. This eliminates the excess numbers to the right of the decimal point. The floor is the closest integer to the decimal number. 1.5 will be 1 and 1.6 will be 2.

A useful function to write is a random range function that takes two numbers and returns a random number between those two numbers. You can use the following code:

public function randRange(min:Number, max:Number):Number {
      var randomNum:Number = Math.floor(Math.random() * (max - min + 1)) + min;
      return randomNum;
}

Using the Random Range function:

for (var i = 0; i < 100; i++) {
      var n:Number = randRange(4, 11);
      trace(n);
} 
Sample program drawing three bands of shapes using randomness:
package {
	import flash.display.*;
	
	public class Exercise1 extends MovieClip {

		public function Exercise1() {
			var i:Number=0;
			while (i < 30) {
                     //draw the circles, lines and curves 30 times each
				drawThing();
				i++;
			}
		}

		public function drawThing():void {
	        //create a random curve 
			this.graphics.lineStyle(randRange(1,8), 0x000000, randRange(.2, .8));
			this.graphics.moveTo(randRange(-50,600),0);
			this.graphics.curveTo(0,randRange(200,300),randRange(-50,600),150);

       	//create a random line 
			this.graphics.lineStyle(randRange(1,6), 0x000000, .5);
			this.graphics.moveTo(randRange(-50,600),200);
			this.graphics.lineTo(randRange(-50,600),300);

			//create a circle 
			this.graphics.beginFill(0xAAAAFF);
			this.graphics.drawCircle(randRange(-50,600),randRange(300,450),randRange(5,30));
			this.graphics.endFill();
		}

		public function randRange(min:Number, max:Number):Number {
			var randomNum:Number = Math.floor(Math.random() * (max - min + 1)) + min;
			return randomNum;
		}
	}
}

Getting a random color:

 this.graphics.beginFill(Math.random()*0xFFFFFF);
 this.graphics.drawRect(100, 100, 50, 50);
 this.graphics.endFill();

 

Controlling Buttons and MovieClips that are on drawn on the stage

1. Create the Button or MovieClip (don't forget to Convert your graphics to a Symbol)
2. Select the symbol on the stage and in the Properties, give it a name in the <Instance Name> box

Ex: myButton is the instance name

In the ActionScript:

myButton.x = 100;
myButton.y =200;     
//this repositions the button on the stage          
myButton.rotation = 30;
myButton.scaleX = 120;
myButton.scaleY = 200;
//this rotates and scales the button on the stage (scaleX = 1 is the original size)              

ActionScript can use Buttons that are stored in the Library but you need to set the Linkage first

1. Create a button with the Up, Over, Down and Hit state
2. Remove the button from the stage
3. Select the Button in the Library
4. Pull down Properties from the top right pull down menu
5. Click the Advanced Button
6. Under Linkage, click ON Export for ActionScript
7. Make the class name the same as the Symbol Name

If you are using CS3, you may be able to Right Mouse Button on the Symbol in the Library and select Linkage

Code:

var theLittleButton:myButton = new myButton();
theLittleButton.x = 250;
theLittleButton.y = 300;
addChild(theLittleButton); 
//the addChild function adds the new button as a child under the stage

You can detect input eventssuch as a click of a button using ActionScript then trigger a function to do something

You must import another library so you can use the built in events in ActionScript

 import flash.events.*;

You make the button just like you did above and then add the Listener to the end of the code. You will need to make a new function to do something when the event occurs.

package {
     import flash.display.*;
     import flash.events.*;
     public class ExA1 extends MovieClip {
           public function ExA1() {
                 // the class of the button is called myButton
                 var theLittleButton:myButton = new myButton();
                      // create an instance called theLittleButton
                 theLittleButton.x=250;
                 theLittleButton.y=300;
                 // must add it to the stage
                 addChild(theLittleButton); 
                 // have the button do something when someone clicks it
                 theLittleButton.addEventListener(MouseEvent.CLICK, clickFunction);
            }
           // this function will be called when the event occurs
           public function clickFunction(theEvent:MouseEvent): void {
                 trace("Clicked the button");
           }
      }
}

The other events you can use are :

MouseEvent.CLICK
MouseEvent.DOUBLE_CLICK
MouseEvent.MOUSE_UP
MouseEvent.MOUSE_DOWN
MouseEvent.MOUSE_OVER
MouseEvent.MOUSE_OUT

You can create text using ActionScrip but you must import the text library first

 import flash.text.*;

Sample code:

package {
	import flash.display.*;
	import flash.events.*;
	import flash.text.*;

	public class ExA1 extends MovieClip {

		public function ExA1() {

			//create an empty text element
			var myText:TextField = new TextField();

			//to change the format of the text you need to make a format object - it takes font, size, color, bold
			var myFormat:TextFormat=new TextFormat("Arial",30,0x000000,true);

			//use the format object to format the words
			myText.defaultTextFormat=myFormat;

			//put the words into the textfield
			myText.text="This is my title";

			//move the text field to where you want it to be
			myText.x=200;
			myText.y=100;

			//put a border on the text field
			myText.border=true;

			//change the width and height
			myText.width=300;
			myText.height=60;

			//make it so you cannot select the text
			myText.selectable=false;

			addChild(myText);
		}
	}
}