very handy reference banner

If you paste any code from this page, make sure to replace the Smart Quote marks "" with ordinary quote marks in your ActionScript editor


trace

trace("some text for the output panel");

outputs:
some text for the output panel

TextField

var myVeryOwnTextfield:TextField = new TextField();
myVeryOwnTextfield.x = 300;
myVeryOwnTextfield.y = 200;
myVeryOwnTextfield.width = 250;
myVeryOwnTextfield.height = 100;
myVeryOwnTextfield.text = “hello, moron!”;
addChild(“myVeryOwnTextfield”);

other useful properties:

myVeryOwnTextfield.border = true;
myVeryOwnTextfield.wordWrap = true;
myVeryOwnTextfield.selectable = true;

TextFormat: setTextFormat

var myFormat:TextFormat= new TextFormat();
myFormat.font = "Arial";
myFormat.size = 16;
myFormat.bold = true;
myFormat.color=0x336633;
myVeryOwnTextfield.setTextFormat(myFormat);

Short version:

myFormat(font, size, color, bold, italic, underline, url, target, align, leftMargin, rightMargin, indent, leading)

Use null or leave out properties you don't want to set. A yet shorter version, in which for instance only font, size, color and bold-or-not are used, might be:

var myFormat:TextFormat = new TextFormat(“Verdana”, 16, 0x33bbaa, true);

TextFormat: defaultTextFormat

For dynamic and input textfields, use:

myVeryOwnTextfield.defaultTextFormat = myFormat;

variable

Declaring, typing and initializing a variable:

var myText:String = "hello, Dolly";
var myAge:Number = 7;

drawing a line

var myLine:Shape = new Shape();
myLine.graphics.lineStyle(3, 0x996666);
myLine.graphics.moveTo(50, 50);
myLine.graphics.lineTo(500, 240);
addChild(myLine);

lineStyle has as parameters: thickness and color
moveTo and lineTo have as parameters x and y coordinates

drawing a rectangle

var myRectangle:Shape = new Shape();
myRectangle.graphics.lineStyle(5,0x6666FF);
myRectangle.graphics.beginFill(0x663366);
myRectangle.graphics.drawRect(150, 100, 240, 180);
myRectangle.graphics.endFill();
addChild(myRectangle);

drawRect has as parameters x coordinate of starting point, y coordinate of starting
point, width, height

drawing a circle

var myCircle:Shape = new Shape();
myCircle.graphics.beginFill(0x00CCFF);
myCircle.graphics.lineStyle(20, 0xCCCC99);
myCircle.graphics.drawCircle(130, 130, 100);
myCircle.graphics.endFill();
addChild(myCircle);

labels

Give a keyframe a label by clicking in it and then putting a name, for instance: startframe, into the Label field in the Properties window. When referencing this label, put it between quotes:

gotoAndPlay("startframe");

event Enter_Frame

stage.addEventListener(Event.ENTER_FRAME, myFunction);
function myFunction(event:Event)
{
instructions
}

event MouseClick

myButton.addEventListener(MouseEvent.CLICK, myFunction);
function myFunction(event:MouseEvent)
{
instructions
}

event Timer_Event

var myTimer:Timer = new Timer();
myTimer.addEventListener(TimerEvent.TIMER, myFunction);
function myFunction(event:TimerEvent):void
{
instructions
}
myTimer.start();

function

constructing a function:

function myFunction()
{
instructions
}

calling a function:

myFunction();

buttons: of the Button type

1. Draw a button on the stage
2. Select the button and hit F8: Convert to Symbol
3. In the Convert to Symbol dialog box, choose type Button
4. If you like, put a textfield on top of the button
5. Doubleclick your button to go into Edit mode
6. Style the button in each of the Up, Over, Down and Hit frames
7. Add an EventListener to the button in actionscript

buttons: of the MovieClip type

1. Draw a button on the stage
2. Select the button and hit F8: Convert to Symbol
3. In the Convert to Symbol dialog box, choose type MovieClip
4. Within the button MovieClip, on top of the layer in which your button sits, create a layer "actions"
5. Create a layer "text". Create a textfield in that layer, on top of your button. Leave it empty (or put some placeholder text in it) but set it to Dynamic and give it an instance name in the Properties window. (If you use static text, then of course set the text directly.)
6. Create a layer "labels". Create keyframes in this layer with the names _up, _over and
_down. Style the button in these keyframes.
7. In actionscript, add an EventListener to the button
8. Also in actionscript, on the main timeline, set the .text property of yourButton.yourTextfield to the desired value
9. Add a stop(); action to the first frame
10. also in the first frame of your MovieClip, set

this.buttonmode = true;

if you have dynamic text in your button, add this to the first frame of your button's code:

this.mouseChildren = false;

Math.random();

To get a whole number between a and b, use

Math.round(Math.random()*(b-a)) + a

arrays

var myArray:Array = new Array(element1, element2, etc);

or

var myArray:Array = [element1, element2, etc];

array: join()

Makes a string out of an array

var myArray:Array = [1, 2, 3, 4];
trace(myArray.join(" and "));

outputs:
1 and 2 and 3 and 4

array: concat()

Adds two arrays together

var a:Array =[100,200,300];
var b:Array =[10,20,30];
var c:Array = a.concat(b);
trace(c);

outputs:
100,200,300,10,20,30

array: push()

adds a new element or elements at the end of the array

var a:Array = ["ruby", "perl"];
a.push("pascal");
a.push("C++");
a.push("java");
trace(a);

outputs:
ruby,perl,pascal,C++,java

array: pop()

removes the last element from the array

var a:Array = ["ruby", "perl", "pascal", "java"];
a.pop();
trace(a);

outputs:
ruby,perl,pascal

array: shift()

Removes the first element from the array. Remaining elements shift one index position down.

var a:Array = ["ruby", "perl", "pascal", "java"];
a.shift();
trace(a);

outputs:
perl,pascal,java

array: unshift()

Adds an element to the beginning of the array. Earlier elements shift one index position up

var a:Array = ["Rongorongo BASIC", "Ruby on 'Roids", "Gentleman's C"];
a.unshift("MethLab");
trace(a);

outputs:
MethLab,Rongorongo BASIC,Ruby on 'Roids,Gentleman's C

array: splice()

With 2 parameters: takes an element or elements out of the array. With 3 parameters: takes an element or elements out of the array and replaces with new element(s).

use: splice(ind, delcount, newEl);
where ind = index of the element to remove
delcount = number of elements to remove
newEl = replacing element(s)

var a:Array = ["Rongorongo BASIC", "Methlab", "Ruby on 'Roids", "Gentleman's C"];
a.splice(0, 2);
trace(a);

outputs:
Ruby on 'Roids,Gentleman's C

var a:Array = ["Rongorongo BASIC", "Methlab", "Ruby on 'Roids", "Gentleman's C"];
a.splice(2, 1, "Lithp");
trace(a);

outputs:
Rongorongo BASIC,Methlab,Lithp,Gentleman's C

array: slice()

Creates a subset of the array

use:slice(ind, endind+1);
where ind = index to start with
endind+1 = last index to use plus 1

var a:Array = [10, 20, 30, 40, 50, 60, 70];
var b:Array = a.slice(3, 5);
trace(b);

outputs:
40,50

array: indexOf()

Gives the index of an element in the array. When the value doesn't exist in the array, -1 is output.

var cars:Array = ["toyota", "renault", "honda", "citroen"];
trace(cars.indexOf("honda"));

outputs:
2

trace(cars.indexOf("volvo"));

outputs:
-1

array: sort()

Sorts alphabetically by default

var cars:Array = ["toyota", "renault", "honda", "citroen"];
cars.sort();
trace(cars);

outputs:
citroen,honda,renault,toyota

sorting numerically:

var cyphers:Array = [3, 20, 117, 5, 78, 36, 2, 99];
cyphers.sort(Array.NUMERIC);
trace(cyphers);

outputs:
2,3,5,20,36,78,99,117

To randomize an array, use a custom sorting function. Example:

var myArray:Array = [1, 12, 2, 3, 43, 4];
myArray.sort(randomize);
function randomize(a:Object, b:Object):Number{
return Math.round(Math.random()*(2)) -1;
}
trace(myArray);

Any other custom sorting function should compare a and b, and return -1 if a should precede b, 1 if b should precede a, and 0 if a and b are equal.

array: for each...in

applies desired instructions to each element in the array

var a:Array = [10, 20, 30, 40, 50, 60, 70];
for each (var myArrayItem:Number in a)
{
trace(myArrayItem);
}

array: forEach()

applies a function to each element in the array

use: myArray.forEach(myFunction);
function myFunction(Element:*, IndexOfElement:int, arr:Array):void
{ instructions }


where Element = any element of your array
IndexOfElement = the index of any element of your array
arr = your Array

var a:Array = [10, 20, 30, 40, 50, 60, 70];
a.forEach(myFunction);
function myFunction(elm:*, ind:int, arr:Array):void
{
trace(elm + 1);
}

associative array

construction:

var enemies:Object = new Object();
enemies.fname = “Hercules”;
enemies.weapon = “crossbow”;
enemies.health = 100;

or

var enemies:Object = new Object();
enemies = {fname: “Hercules”, weapon: “crossbow”, health: 100};

addressing an element:

trace(enemies.fname);  

or

trace(enemies["fname"]);  

looping through an associative array

var enemies:Object = new Object();
enemies = {fname: “Hercules”, weapon: “crossbow”, health: 100};

for (var qual:String in enemies) {
trace(qual + “:” + enemies[qual]);
}

changing a color dynamically

var myColorTransformThingy:ColorTransform = new ColorTransform();
myColorTransformThingy.
color = 0x1A4BB6;
myMC.
transform.colorTransform = myColorTransformThingy;

random color

var myRandomColor:Color = Math.random() * 0xFFFFFF;

rotation

myMovieClip.rotation = 180;

rotates the clip by 180 degrees

width and height

myMovieClip.width = 200;

sets the width to 200 pixels. Same with height.

alpha

A value between 0 and 1

myMovieClip.alpha = .7;

sets the clip to 70% visibility

scale

works percentage-wise

myMovieClip.scaleX = 2;

sets the clip to 200% its width

myMovieClip.scaleY = -.5;

sets the clip to half its width and flips it vertically

for...loop

do something 40 times:

for (var i =0;  i<40;  i++)
{
instructions
}

nested for...loop

place 36 movieclips at 50 pixels distance to each other, both vertically and horizontally:

for (var i = 0; i < 6 ; i++){
for (var j = 0; j < 6; j++){
var clip:MovieClip = new MovieClip();
clip.x = i*50 ;
clip.y = j*50;
addChild(clip);
}

keyboard_event

stage.addEventListener(KeyboardEvent.KEY_DOWN, onDown);
function onDown(evt:KeyboardEvent):void
{
instructions
}

some keyboard event codes

evt.Keycode:

keyboard.RIGHT or 39   right arrow
keyboard.LEFT or 37    left arrow
keyboard.UP or 38      up arrow
keyboard.DOWN or 40    down arrow
13                     Return key
8                        Backspace
16                       Shift

N.B.: within Flash, keycode numbers sometimes don't work as expected. If so, test the movie as a standalone.

if... statement

if (randomnum == 1) {
instructions
}

if...else statement

if (randomnum == 1) {
instructions;
}
else {
trace("no show today");
}

String

var myString:String = "what's all this, then?";

putting a Symbol from the Library on the stage with AS

When converting the object to a Symbol in Flash, name it and tick off "Export for ActionScript" in the popup window. If a warning dialog box pops up, click OK. In your actionscript, to create an instance code:

var myVarName:Type = new Type();

in which myVarName is the instance name and Type is MovieClip, Button or Shape.

The ComboBox component

Drag a ComboBox onto the stage. In the Component Parameters window, click on the pencil symbol next to dataProvider. Populate the dataProvider as follows: for every "Name" in the left hand column, put a valuename in the field "label", in the right hand column. Right underneath that, in the "data" label, put the value you want to be associated with that name. To address these two things in actionscript:

myComboBox.addEventListener(Event.CHANGE, doSomething);
function doSomething(e:Event):void{
trace(e.target.selectedItem.label);
trace(e.target.selectedItem.data);
}

Styling the ComboBox

For the label on the ComboBox, make a TextFormat and apply it in this way:

myComboBox.textField.setStyle(“textFormat”, myTextFormat);

Change the color of the ComboBox:

var myCTF:ColorTransform = new ColorTransform(0×000099);
myComboBox.transform.colorTransform = myCTF;

Distance between two points

The distance between point a and point b is

var dist:Number;
var xdiff:Number;
var ydiff:Number;

xdiff = b.x – a.x;
ydiff = b.y – a.y;
dist = Math.sqrt(xdiff*xdiff + ydiff*ydiff);

and can also be found with

var Point1:Point = new Point(a.x, a.y);
var Point2:Point = new Point(b.x, b.y);
var dist:Number;
dist = Point.distance(Point1, Point2);

Tweening

Use these import statements:

import fl.transitions.Tween;
import fl.transitions.easing.*;

For every property to be tweened, compose a tween like so:

var t1:Tween = new Tween(cog, “x”Regular.easeInOut, 100, 580, 3, true);

in which the parameters are
1. object to be tweened
2. property
3. easing type
4. starting value
5. ending value
6. duration
7. true if you want duration in seconds, false if you want duration in frames

Absolute coordinates of an object

For an existing movieclip myClip:

var clipPoint:Point = new Point(myClip.x, myClip.y);
var clipAbs = localToGlobal(clipPoint);

Dragging a movieclip: startDrag()

clip.addEventListener(MouseEvent.MOUSE_DOWN, onDown);
function onDown(event:MouseEvent):void {
clip.startDrag();
}
clip.addEventListener(MouseEvent.MOUSE_UP, onUp);
function onUp(event:MouseEvent):void {
clip.stopDrag();
}

Dragging a mc: finding the dropTarget

For dynamically added targets with .name property:

function onUp(event:MouseEvent):void {
clip.stopDrag();
trace(clip.dropTarget.name);
}

For targets added on the stage:

function onUp(event:MouseEvent):void {
clip.stopDrag();
trace(clip.dropTarget.parent.name);
}

Dragging a movieclip by mouse-follow

var offsetX:Number;
var offsetY:Number;

clip.addEventListener(MouseEvent.MOUSE_DOWN, startDragging);
function startDragging(event:MouseEvent):void{
offsetX = mouseX - clip.x;
offsetY = mouseY - clip.y;

stage.addEventListener(MouseEvent.MOUSE_MOVE, dragClip);
function dragClip(event:MouseEvent):void{
clip.x = mouseX - offsetX;
clip.y = mouseY - offsetY;
}

clip.addEventListener(MouseEvent.MOUSE_UP, stopDragging);
function stopDragging(event:MouseEvent):void{
stage.removeEventListener(MouseEvent.MOUSE_MOVE, dragClip);
}

Radians

degrees = radians * 180/Math.PI
radians = degrees*Math.PI/180

movement along an angle

var myAngle = some angle
var myAngleInRad = Math.PI/myAngle;

myClip.= myClip.x + Math.cos(myAngleInRad)*speed;
myClip.y = myClip.y + Math.sin(myAngleInRad)*speed;

circular movement

To have the clip planet revolve around the center of your stage at a radius of 150:

var radius:Number = 150;
var angle:Number = 1;
var centerX = stage.stageWidth/2;
var centerY = stage.stageHeight/2;
var speed = 3;

stage.addEventListener(Event.ENTER_FRAME, go);
function go(e:Event):void{
var angleInRad:Number = angleInDegrees*Math.PI/180;
planet.x = centerX + radius*Math.cos(angle);
planet.y = centerY + radius*Math.sin(angle);
angle = angle + speed/57;
}

(In the last line, speed was divided by 57 to give it a reasonable number; otherwise, since we used radians and not degrees, speed would have to be set at impractically small, fractional numbers)

Following the mouse (and turning at stage ends)

stage.addEventListener(Event.ENTER_FRAME, moveClip);
function moveClip(e:Event):void{

clip.x = mouseX;

if (mouseX > stage.stageWidth - clip.width / 2) {
clip.scaleX = -1;
clip.x = stage.stageWidth - clip.width/2;      
}
if (mouseX <= clip.width/2) {
clip.scaleX = 1;
clip.x = clip.width/2;    
}
}

Similar for y movement.

Following the mouse at a distance, and turning at stage ends and when the object changes direction

var prevX:Number;
var curX:Number;
var prevY:Number;
var curY:Number;

stage.addEventListener(Event.ENTER_FRAME, moveClip);
function moveClip(e:Event) {

curX = mouseX;
curY = mouseY;

if (curX > prevX){clip.scaleX = 1;}
if (curX < prevX){clip.scaleX = -1;}
if (curY > prevY){clip.scaleY = 1;}
if (curY < prevY){clip.scaleY = -1;}

prevX = curX;
prevY = curY;

var dx:Number = mouseX - clip.x;
clip.x += dx / 5;
var dy:Number = mouseY - clip.y;
clip.y += dy / 5;

if (mouseX > stage.stageWidth - clip.width / 2) {
clip.scaleX = -1;
clip.x = stage.stageWidth - clip.width/2;
}
if (mouseX <= clip.width/2) {
clip.scaleX = 1;
clip.x = clip.width/2;
}

if (mouseY > stage.stageHeight - clip.height / 2) {
clip.scaleY = -1;
clip.y = stage.stageHeight - clip.height/2;
}
if (mouseY <= clip.height/2) {
clip.scaleY = 1;
clip.y = clip.height/2;
}
}

Detecting mouse movement direction

var prevX:Number;
var curX:Number;
var prevY:Number;
var curY:Number;

stage.addEventListener(Event.ENTER_FRAME, getDirection);
function getDirection(e:Event) {

curX = mouseX;
curY = mouseY;

if (curX > prevX){trace("going right";}
if (curX < prevX){trace("going left";}
if (curY > prevY){trace("going down");}
if (curY < prevY){trace("going up");}

prevX = curX;
prevY = curY;
}

hitTestObject

For two objects, beam and block:

stage.addEventListener(Event.ENTER_FRAME, hitCheck);
function hitCheck(e:Event):void{
if (beam.hitTestObject(block) == true) {
trace("we have a hit)";
}
}

for 4 objects ball1 to ball4 against one object wall:

var clipArray:Array = [ball1,ball2,ball3,ball4];

for (var i:Number = 0; i < clipArray.length; i++){
clipArray[i].addEventListener(Event.ENTER_FRAME, whatHits);
function whatHits(e:Event):void{
var clip:MovieClip = MovieClip(e.target);
if (clip.hitTestObject(wall)){
trace(clip.name + “hit the wall”);
}
}
}

hitTestPoint

To test whether the bounding box of a movieclip touches a certain point (300,20):

myClip.hitTestPoint(300, 20, false);

To test whether the actual shape of the clip touches that point:

myClip.hitTestPoint(300, 20, true);

To test whether the mouse is within the bounding box of an object:

myClip.hitTestPoint(mouseXmouseYfalse);

To test whether the mouse touches any part of the shape of that object:

myClip.hitTestPoint(mouseX, mouseY, true);

 

 

 


 

 

 

 

 

 

 

 

 

 

 

 


\