Latest snippets

Number.toFixed()

var someValue:Number = 2.0480531167374427;

// want to show only 3 decimal places?
trace(someValue.toFixed(3)); // outputs 2.048

An easy way to get rid of extra decimal values. This is useful when you want to show decimal values in text fields. I only recently noticed this in the docs, I used to do this type of thing:

trace(int(someValue * 1000) / 1000);  // outputs 2.048

XOR Color Invert

var yellow:uint = 0xFFFF00;

// draws yellow circle
with(graphics) beginFill(yellow), drawCircle(100,100,50);

// invert the color using XOR assignment
// yellow becomes 0x0000FF
yellow ^= 0xFFFFFF;

// draws blue  circle 
with(graphics) beginFill(yellow), drawCircle(200,100,50);

Just a fun use for XOR. You could also do it without XOR assignment:

with(graphics) beginFill(yellow ^ 0xFFFFFF), drawCircle(200,100,50);

Playing a little with bitwise operators is a good way to make sure you understand them. Try tweaking this trace statement:

trace((0x543210 ^ 0xFFFFFF).toString(16));

If you’d like to read about bitwise operators, I recommend wikipedia’s article.

Toggle .visible

// toggle a DisplayObject's visible property
var shape = new Shape();

shape.visible = !shape.visible;
trace(shape.visible); // outputs false

shape.visible = !shape.visible;
trace(shape.visible); // outputs true

shape.visible = !shape.visible;
trace(shape.visible); // outputs false

shape.visible = !shape.visible;
trace(shape.visible);  // outputs true

This is pretty obvious to anyone with a full understanding of the ! operator. It’s useful for things
like checkboxes and other types of toggle buttons. The first time I ever encountered this technique
was in processing source… in one of the demos on toxi.co.uk

Here’s another quick example you can run in your timeline:

var circle:Shape =  new Shape();
circle.graphics.beginFill(0xFF0000);
circle.graphics.drawCircle(0, 0,10);
circle.x = 80;
circle.y = 105;
addChild(circle)

var btn:TextField = new TextField();
btn.text = "click this text to toggle red circle's visibility";
btn.x = btn.y = 100;
btn.selectable = false;
btn.border = true;
btn.autoSize = TextFieldAutoSize.LEFT;
addChild(btn);

btn.addEventListener(MouseEvent.CLICK, onClick);
function onClick(evt:MouseEvent):void{
	circle.visible = !circle.visible;
}

Because “not false” is true.

Multiple Graphics Class Calls

// draw red circle
with (graphics) beginFill(0xFF0000), drawCircle(200,100,30);

// draw 100 gray circles
with (graphics) for (var i:int = 0; i<100; i++) beginFill(0x666666), drawCircle(Math.random()*200, Math.random()*200, Math.random()*10), endFill();

// draw a few lines
with (graphics) lineStyle(0, 0x000000), moveTo(10,210), lineTo(20,300), lineTo(30,210), lineTo(40,300), lineTo(50,210), lineTo(60,300);

Sometimes it’s tedious to write lines and lines of Graphics class method calls. Using a with statement you can reduce these calls into one long (not very readable) line of code.

More readable example:

with(graphics) {
	beginFill(0xFF0000);
	drawRect(0,0,100,100);
	endFill();
	beginFill(0xFFFF00);
    drawRect(10,10,80,80);
	endFill();
	beginFill(0x0000FF);
	drawCircle(50,50,40);
}

Click Listener

var e:String = "addEventListener";

stage[e]("click", function():void{
	trace("clicked", arguments[0]);
});

Strange code to do a click listener. arguments[0] is the event object. (Check out the “warning” page for more info about this).

stage.addEventListener(MouseEvent.CLICK, onStageClick);
function onStageClick(evt:MouseEvent):void {
	trace("clicked", evt);
}

Normal way.

2D Array Map

var col:Array = [0x000000, 0xCCCCCC, 0xFF0000, 0xCCCC00, 0x000055, 0x00CCCC];

var map:Array = new Array();
map[0] = [0,0,0,0,0,0,0,0,0,0];
map[1] = [0,0,0,0,0,0,0,0,0,0];
map[2] = [0,5,4,5,4,5,4,5,4,0];
map[3] = [0,4,4,4,4,4,4,4,4,0];
map[4] = [0,4,0,0,0,0,0,0,4,0];
map[5] = [0,3,2,3,2,3,2,3,2,0];
map[6] = [1,1,1,1,1,1,1,1,1,1];
map[7] = [0,2,2,2,2,2,2,2,2,0];
map[8] = [1,1,1,1,1,1,1,1,1,1];

for (var i:int = 0; i<map.length; i++){
	for (var j:int = 0; j<map[i].length; j++){
		graphics.beginFill(col[map[i][j]]);
		graphics.drawRect(j * 10, i * 10, 10, 10);
	}
}

Use a 2D array to draw a map of colored rectangles. Lots of stuff you can do with this – like adding game tiles instead of drawing colored rects:

// add clip with multiple frames - each containing a tile graphic
var tile:MovieClip = TileClip();
tile.gotoAndStop(map[i][j]+1);
addChild(tile);

DisplayObject describeType()

for each(var prop:String in describeType(DisplayObject).factory.accessor.@name){
	trace(prop);
}
/* outputs
scaleY
mouseX
mouseY
mask
rotation
alpha
transform
blendMode
x
root
loaderInfo
width
z
rotationX
scale9Grid
filters
rotationY
y
stage
scaleZ
parent
accessibilityProperties
scrollRect
rotationZ
height
name
opaqueBackground
blendShader
cacheAsBitmap
visible
scaleX
*/

I First saw describeType() at senocular’s AS3 Tip of the Day on Kirupa.

Random Choice

function randomChoice(...args:Array):*{
	return args[int(Math.random()*args.length)];
}

// choose randomly from a number of different values
var val:* = randomChoice(10, "Hello", "0xFF0000", 1000);

// choose a random color (in this case red, green or blue)
var randColor:uint = randomChoice(0xFF0000, 0x00FF00, 0x0000FF);

trace(val);
trace(randColor);

The function randomChoice() takes any number of arguments and spits one of them back randomly. Just a handy function to have around… I especially like to use this function to choose from a handful of colors.

Rect vs Ellipse

for (var i:int = 0; i<100; i++){
	graphics.lineStyle(0,0);
	graphics[["drawEllipse", "drawRect"][int(Math.random()*2)]](Math.random()*400, Math.random()*300, Math.random()*100,Math.random()*100)
}

/*
WARNING: This code was written for fun. Use at your own risk. 
*/

And a more readable version:

var methodChoices:Array = ["drawEllipse", "drawRect"];
var method:String;
var xp:Number, yp:Number, w:Number, h:Number;
for (var i:int = 0; i<100; i++){
	method = methodChoices[int(Math.random()*methodChoices.length)];
	graphics.lineStyle(0,0);
	xp = Math.random()*400;
	yp = Math.random()*300;
	w = Math.random()*100; 
	h = Math.random()*100;
	graphics[method](xp, yp, w, h)
}

/*
WARNING: This code was written for fun. Use at your own risk. 
*/

Here I use yesterdays associative array function call technique to do something different. Not really all that useful, but interesting….

Associative Array Function Call

for (var i:int = 0; i<4; i++){
	this["phase"+i]();
}

function phase0():void{
	trace("phase 0");
}
function phase1():void{
	trace("phase 1");
}
function phase2():void{
	trace("phase 2");
}
function phase3():void{
	trace("phase 3");
}

/*
will output:
phase 0
phase 1
phase 2
phase 3
*/

/*
WARNING: This code was written for fun. Use at your own risk.
*/

I was pleasantly surprised back in the AS1 days… when I discovered that associative array syntax worked along with function calls (why wouldn’t it?). There are some interesting tricks you can do with this technique…. will post some later….