Browse the notebook

Month: November 2008

10,000 35 ways, .toString(radix);

for(var i:int = 2; i<37; i++){
	trace((10000).toString(i));
}
/*
outputs:
10011100010000
111201101
2130100
310000
114144
41104
23420
14641
10000
7571
5954
4723
3904
2e6a
2710
20a4
1cfa
18d6
1500
11e4
kec
iki
h8g
g00
ekg
dja
cl4
bpo
b3a
aci
9og
961
8m4
85p
7ps
*/

I had either totally forgotten about or never known about the Number, uint, int etc… .toString() radix argument. Brock mentioned it to me in conversation and I’ve been having fun with it ever since. It’s especially nice for tracing out hex numbers:

var red:Number = 0xFF0000;
trace("decimal:");
trace(red);
trace("hex:");
trace(red.toString(16));
Read snippet: 10,000 35 ways, .toString(radix);

Mini Tween Engine

var box:MovieClip = new MovieClip();
box.graphics.beginFill(0xFF0000);
box.graphics.drawRect(-25,-25,50,50);
addChild(box);

stage.addEventListener(MouseEvent.CLICK, onStageDown);
function onStageDown(evt:MouseEvent):void{
	moveTo(box, "x", 300, 2, Back.easeOut);
	moveTo(box, "y", 200, 2, Back.easeOut);
	moveTo(box, "scaleX", 2, 2, Back.easeOut);
	moveTo(box, "rotation", 180, 2, Quartic.easeOut, onDone);
	stage.removeEventListener(MouseEvent.CLICK, onStageDown);
}
					 
function onDone():void {
	moveTo(box, "x", 120, 2, Back.easeIn);
}

//
// -- TWEEN ENGINE
//
import fl.motion.easing.*;

// movieClip to tween, property to tween, final value for the property, duration of tween,
// ease type, complete callback function
function moveTo(mc:MovieClip, prop:String, dest:Number, duration:Number, ease=null, 
				           completeFunction:Function=null):void {
	if (ease == null) {
		ease = Quartic.easeOut;
	}
	// use the property to make all var names unique
	mc["begin" + prop] = mc[prop];
	mc["change" + prop] =  dest - mc[prop];
	mc["time" + prop] = 0;
	mc["startTime" + prop] = getTimer();
	mc["duration" + prop] = duration;
	mc["prop"] = prop;
	mc["ease" + prop] = ease;
	mc["complete_" + prop] = completeFunction;
	mc.addEventListener(Event.ENTER_FRAME, makeMotionFunction(mc, prop));
}

function makeMotionFunction(mc:MovieClip, prop:String):Function {
	return function(evt:Event){
		if (mc["time" +prop] <= mc["duration"+ prop]){ 
		   mc[prop]=mc["ease" + prop](mc["time" + prop], mc["begin" +prop], mc["change"+ prop], mc["duration"+ prop]);
		} else {
			var completeFunction:Function = mc["complete_"+prop];
			if (completeFunction!=null){
			  completeFunction();
			}
			mc.removeEventListener(Event.ENTER_FRAME, arguments.callee);
			// see how long the tween took
		    //trace(mc["time"+prop]);
		}
		   mc["time" + prop] = (getTimer() - mc["startTime" + prop]) / 1000;
	};
}
/*
WARNING: This code was written for fun. Use at your own risk.
*/

This code uses a ~35 line tweening engine. I wrote this for fun a few weeks back. It works by creating dynamic variables on the MovieClip that it tweens. The dynamic variables and the square bracket syntax cause it to be pretty slow. Definitely not a substitute for a real tweening engine… like TweenLite.

I wouldn’t recommend using this for anything other than playing around. See warning page for more info.

Read snippet: Mini Tween Engine

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
Read snippet: Number.toFixed()

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.

Read snippet: XOR Color Invert

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.

Read snippet: Toggle .visible

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);
}
Read snippet: Multiple Graphics Class Calls

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.

Read snippet: Click Listener

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);
Read snippet: 2D Array Map

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.

Read snippet: DisplayObject describeType()

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.

Read snippet: Random Choice