RSS

advertise-here_03.jpg

advertise-here_06.jpg

advertise-here_06.jpg

AS3Cheatsheet
How to create basic class
How to access element from action script
How to convert number to string
How to load xml file
How to make element ignored by mouse
How to read input parameters from url query string
How to round numbers with precision
How to make element dragable
How to store data in movie clip
How to change color of movie clip
How to display child elements
How to match elements by regexp
How to make string search and replace by regexp
How to make search and replace by regexp and function
How to make tween color animation of movie clip
How to make first letter capital
How to extend base class with your method
How to read data from xml
How to control element overlay order
How to create element from library
How to make hand cursor over element
How to set value of a dynamic text field
How to access subsymbol of symbol
How to navigate to link
How to call javascript function from action script 3
How to animate movieclip position or any other attribute
How to execute command after delay
How to play animation from random point
How to make text animation smooth
How to use associative arrays
How to dynamicly load images
How to create and format text field
How to create invisible covering layer
How to create copy of Loader object
How to play animation backward

How to create basic class

create fallowing file structure in your directory where you have your *.fla file

lib/Main.as

Paste to lib/Main.as example contents:

package lib {
import flash.display.MovieClip;

public class Main extends MovieClip {
public function Main ():void {
trace('Hello world from Action Script 3');
}
}
}

in document properties window type: lib.Main in "Class" input field

How to access element from action script

Draw any element on a stage
Right click on it and with the "selection tool" and click "Convert to symbol" and click "ok"
Click on it and in property window set its unique "Instance name" for example "test"
Access it from as3 for example

test.x = 100;
test.y = 100;

How to convert number to string

For example if you would write:

var s:String = 1.2345;

You will get: "Implicit coercion of a value of type Number to an unrelated type String." Solution is to concat number with empty string:

var s:String = ""+1.2345;

How to load xml file

Create file stdin.xml with example data eg:

<data>
<item id="1" extra="data1">content 1</item>
<item id="2" extra="data2">content 2</item>
<item id="3" extra="data3">content 3</item>
</data>

In the Asction Script 3 file:

import flash.events.Event;
import flash.net.URLLoader;
import flash.net.URLRequest;

// in constructor:

var xmlLoader:URLLoader = new URLLoader();
xmlLoader.addEventListener(Event.COMPLETE, LoadXML);
xmlLoader.load(new URLRequest("stdin.xml"))

// ... and somewhere later

function LoadXML(e:Event):void {
trace(e.target.data);

var xml = new XML(e.target.data);
trace(xml);
}

to see how to process such file go here

How to make element ignored by mouse

test.mouseEnabled = false; 
test.mouseChildren = false;

How to read input parameters from url query string

Supose you have ambeded your flash like test.swf?test1=Works

trace("parametr test1: "+this.loaderInfo.parameters.test1);

How to round numbers with precision

Regular Math.round subroutine doesnt provide precision. To simulate it you can use:

function round(n:Number, precision:int):Number {
var pow:int = Math.pow(10, precision);
return Math.round(n * pow) / pow;
}

trace("1.23456 precision 2 is "+round(1.23456, 2)); // 1.24
trace("1.23456 precision 4 is "+round(1.23456, 4)); // 1.2346
trace("1.23456 precision 0 is "+round(1.23456, 0)); // 1

How to make element dragable

Supose you have element names test2
Its best to set event listeners to whole scene reather than to dragable element

import flash.events.MouseEvent;

// ...

test.addEventListener(MouseEvent.MOUSE_DOWN, test_mouse_down);

public function test_mouse_down (e:MouseEvent):void {
stage.addEventListener(MouseEvent.MOUSE_MOVE, test_mouse_move);
stage.addEventListener(MouseEvent.MOUSE_UP, test_mouse_up);
}

public function test_mouse_move (e:MouseEvent):void {
test.x = e.stageX - ( test.width / 2 );
test.y = e.stageY - ( test.height / 2 );
}

public function test_mouse_up (e:MouseEvent):void {
stage.removeEventListener(MouseEvent.MOUSE_MOVE, test_mouse_move);
stage.removeEventListener(MouseEvent.MOUSE_UP, test_mouse_up);
}

How to store data in movie clip

Trick is that you can write to any propery which starts with "storeData" and it will be saved!

test.storeDataSecret = "John is the killer";
trace(test.storeDataSecret);

How to change color of movie clip

import flash.geom.ColorTransform;

function setRGB(e:Object, color:uint):void {
var c:ColorTransform = e.transform.colorTransform;
c.color = color;
e.transform.colorTransform = c;
}
setRGB(test, 0xc5cac3);

How to display child elements

for (var i=0; i<this.numChildren; i++) {
    trace("child "+i+" name is "+this.getChildAt(i).name);
}

How to match elements by regexp

var pattern:RegExp = new RegExp("^(A|b|8)");
trace("Ala".match(pattern));
trace("algebra".match(pattern));
trace("8-Ball".match(pattern));
trace("banan".match(pattern));

How to make string search and replace by regexp

For example to turn all repeated white signs to space:

trace( "Ala     ma      kota".replace(/[[:blank:]]+/g, ' '));

How to make search and replace by regexp and function

Sometimes what you have to do is impossible by simple search and replace then you can use function reference:

trace(
"aabb ccddeeff".replace(
/(^|[[:blank:]])([[:alnum:]])/g,
 function ():String { return arguments[1]+arguments[2].toUpperCase(); }
)
);

returns "aAbb cCddeeff"

How to make tween color animation of movie clip

import fl.transitions.Tween;
import fl.transitions.TweenEvent;
import fl.transitions.easing.*;
import flash.geom.ColorTransform;

// ... in class variables

var startColor:ColorTransform = new ColorTransform(); // default color, no tint
var endColor:ColorTransform = new ColorTransform();

// ... in constructor

startColor.color = 0xff8833;
endColor.color = 0x0066ff;

var tween:Tween = new Tween(test, "", Strong.easeOut, 1, 0, 300);
tween.addEventListener(TweenEvent.MOTION_CHANGE, color_tween);

// - and later in a code -

function color_tween(event:TweenEvent):void {
event.currentTarget.obj.transform.colorTransform = color_transform(startColor, endColor, event.target.position);
}

function color_transform(from:ColorTransform, to:ColorTransform, step:Number):ColorTransform {
var r:ColorTransform = new ColorTransform();
r.redMultiplier = from.redMultiplier + (to.redMultiplier - from.redMultiplier) * step;
r.greenMultiplier = from.greenMultiplier + (to.greenMultiplier - from.greenMultiplier) * step;
r.blueMultiplier = from.blueMultiplier + (to.blueMultiplier - from.blueMultiplier) * step;
r.alphaMultiplier = from.alphaMultiplier + (to.alphaMultiplier - from.alphaMultiplier) * step;
r.redOffset = from.redOffset + (to.redOffset - from.redOffset) * step;
r.greenOffset = from.greenOffset + (to.greenOffset - from.greenOffset) * step;
r.blueOffset = from.blueOffset + (to.blueOffset - from.blueOffset) * step;
r.alphaOffset = from.alphaOffset + (to.alphaOffset - from.alphaOffset) * step;

return r;
}

How to make first letter capital

function ucfirst(s:String):String {
return s.substr(0, 1).toUpperCase() + s.substr(1);
}

trace(ucfirst('ala ma kota'));

How to extend base class with your method

Lets for example add ucfirst method to String class

String.prototype.ucfirst = function():String {
var s:String = this;
return s.substr(0, 1).toUpperCase() + s.substr(1);
}

var s = 'ala ma kota';
trace( s.ucfirst() );

How to read data from xml

var data:String = "<data>"
+" <item id='1' extra='data1'>content 1</item>"
+"    <item id='2' extra='data2'>content 2</item>"
+"    <item id='3' extra='data3'>content 3</item>"
+"</data>";

var xml = new XML(data);
for each (var property:XML in xml.item) { // iterate over all elements
trace(">"+property.@id+" - "+property.@extra+" - "+property.text());
}

// get element of specific attribute value

trace(xml.item.(@id==2).@extra);

How to control element overlay order

Element overlay depends on order in child index table. To move some el,ement forward you just have to swap it:

this.swapChildrenAt(this.getChildIndex(test), this.numChildren-1);

How to create element from library

You have to create element - using "selection tool" right click on it and select "convert to symbol" in "advanced" section check "export for actionscript"  and in "class" field type "myobject" and press "ok". Now you can use this element like:

var t:myobject = new myobject();
t.x = 99;
t.y = 99;
addChild(t);

How to make hand cursor over element

test.buttonMode = true;
test.useHandCursor = true;

How to set value of a dynamic text field

textfield1.text = "Hello World from Action Script 3";

If after this operation text in text field is broken that means that you have to go to fla file and near font selector press "Embed" and chose charaters to embed in your swf file

How to access subsymbol of symbol

If you created symbol "test" in your fla file and inside of it you created symbol named "subsymbol" you can eccess them by:

trace(test.subsymbol);

How to navigate to link

Suppose you want to navigate to agivera.pl after clicking on element ``test''

import flash.events.MouseEvent;
import flash.net.navigateToURL;
import flash.net.URLRequest;

// in constructor

test.addEventListener(MouseEvent.MOUSE_UP, test_up);

// in package

function test_up (e:MouseEvent):void {
var link:URLRequest;
link = new URLRequest("http://agivera.pl");
navigateToURL(link, "_parent");
}

How to call javascript function from action script 3

Suppose you want to call javascript subroutine with the X coordinates of flash click

import flash.net.navigateToURL;
import flash.net.URLRequest;
import flash.events.MouseEvent;

// in constructor

test.addEventListener(MouseEvent.MOUSE_UP, test_up);

// in package

function test_up (e:MouseEvent):void {
var s:String = "javascript:window.alert('Hello message from Action Script!')";
var link:URLRequest = new URLRequest(s);
navigateToURL(link, "_parent");
}

How to animate movieclip position or any other attribute

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

var tween_x:Tween = new Tween(test, "x", Back.easeOut, test.x, 300, 100);
var tween_y:Tween = new Tween(test, "y", Back.easeOut, test.y, 300, 100);

// later you can for example use:
// tween_x.stop(); to stap animation or tween_x.jojo(); to make it backwards or tween_x.looping = true; to make it loop

How to execute command after delay

import flash.utils.*;

var timeoutId:uint;

timeoutId = setTimeout(function ():void { trace("im displayed after 1s"); timeoutId=0; }, 1000);

// or

timeoutId = setTimeout(name_of_function_to_call, 1000);

// or

timeoutId = setTimeout(function ():void { name_of_function_to_call(arg1, arg2); }, 1000);

In meantime you can use this to abort timeout: if (timeoutId>0) { clearTimeout(timeoutId); }

How to play animation from random point

test.gotoAndPlay(Math.floor(Math.random() * test.totalFrames)+1);

How to make text animation smooth

If your animation of element with text is scratchy you have to set option "Optimaze for animation"

How to use associative arrays

var rh_args:Object= new Object();
rh_args.secret = 'problem';

trace( rh_args.secret );

How to dynamicly load images

import flash.display.Loader;
import flash.events.Event;
import flash.events.ProgressEvent;
import flash.net.URLRequest;

// in class variables

var loader:Loader;

// in constructor

loader = new Loader();
loader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, loader_progress);
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, loader_complete);

var req:URLRequest = new URLRequest("example.jpg"); // has to be in the same directory as fla/swf file
loader.load(req);

// in class body

function loader_progress(e:ProgressEvent) {
trace(e.bytesLoaded, e.bytesTotal);
}

function loader_complete(e:Event) {
addChild(e.currentTarget.loader);
}

How to create and format text field

import flash.text.TextFormat;
import flash.text.TextField;
import flash.text.TextFieldAutoSize;

// in constructor

var text:TextField = new TextField();
text.text = "hello world";
text.autoSize = TextFieldAutoSize.LEFT;
text.selectable = false;
text.multiline = true;

addChild(text);
var newFormat:TextFormat = new TextFormat();
newFormat.color = 0x000000;
newFormat.size = 10;
newFormat.font = "Tahoma";
newFormat.underline = true;
newFormat.italic = true;

text.setTextFormat(newFormat);

How to create invisible covering layer

var clickable:MovieClip = new MovieClip();
clickable.x = 100;
clickable.y = 100;
// clickable.width = 50; // be warned that seting width and height brokes this layer! Dont use it!
// clickable.height = 55;
clickable.buttonMode = true;
clickable.useHandCursor = true;
clickable.graphics.beginFill(0xFFFFFF, 0);
clickable.graphics.drawRect(0, 0, 100, 100);
clickable.graphics.endFill();
addChild(clickable);

How to create copy of Loader object

import flash.display.Bitmap;

// in package

function clone (l:Loader):Bitmap {
return new Bitmap( Bitmap( l.content ).bitmapData );
}

// in code

var empty_loader:Loader = new Loader();
empty_loader = clone(already_loaded_loader);

How to play animation backward

// in code

gotoAndStop(this.totalFrames-1);
this.addEventListener(Event.ENTER_FRAME, play_tobegin);
play();

// in package

function play_tobegin (e:Event):void {
if (this.currentFrame==1) {
this.removeEventListener(Event.ENTER_FRAME, play_tobegin);
}
this.prevFrame();
}
Copyright © as3cheatsheet.agivera.pl 2010. All rights reserved.
Project and realization: agivera.pl