Latest snippets

2D Vector

var map:Vector.<Vector.<int>> = new Vector.<Vector.<int>>();
map[0] = new Vector.<int>();
map[0].push(1);
map[0].push(0);
map[0].push(0);

map[1] = new Vector.<int>();
map[1].push(0);
map[1].push(1);
map[1].push(0);

map[2] = new Vector.<int>();
map[2].push(0);
map[2].push(0);
map[2].push(1);

/*
map:
1,0,0
0,1,0
0,0,1
*/

This creates a two dimensional Vector of ints (flash 10 player only). The first line is the real snippet… took me a few minutes to get the syntax right the first time I needed a 2D Vector.

Draw Spiral

stage.frameRate = 30;
var xp:Number = 0;
var yp:Number = 0;
var counter:Number = 0;
graphics.lineStyle(0,0x999999);
graphics.moveTo(200,200);
addEventListener(Event.ENTER_FRAME, onLoop);
function onLoop(evt:Event):void {
	for (var i:int = 0; i < 20; i++) {
		counter += .05;
		xp=200 + counter * Math.cos(counter);
		yp=200 + counter * Math.sin(counter);
		graphics.lineTo(xp, yp);
	}
	if (counter > 400) {
		removeEventListener(Event.ENTER_FRAME, onLoop);
	}
}

Draws a spiral over time.

Object.prototype Crap

Object.prototype.myVar = "I am a variable";

var s:Sprite = new Sprite();
 
trace(Object(s).myVar);

var v:Video = new Video();
trace(Object(v).myVar);

This…. should not be done… and setting myVar like this:

Object(s).myVar = "hello";

Will cause an error….

I keep a folder on my laptop for this website….. when I have a random snippet idea I put it in this folder…. Every couple of weeks I go through this folder and turn select snippets into posts…. when I rediscovered this snippet today it really made me laugh….

Random Walk

var xp:Number=Math.random() * stage.stageWidth;
var yp:Number=Math.random() * stage.stageHeight;
graphics.lineStyle(0,0x000000);
graphics.moveTo(xp, yp);
addEventListener(Event.ENTER_FRAME, onLoop);
function onLoop(evt:Event):void {
	xp+=Math.random()*10-5;
	yp+=Math.random()*10-5;
	graphics.lineTo(xp, yp);
}

Nothing special here, but its good to know that this technique has a name… and that it’s NOT Brownian Motion… more here.

Format Phone #

var phoneField:TextField = new TextField();
with (phoneField) {
	type=TextFieldType.INPUT;
	maxChars=12;
	restrict="0-9";
	border=true;
	width=100;
	height=20;
	x=y=20;
}
addChild(phoneField);

phoneField.addEventListener(TextEvent.TEXT_INPUT, onInput);

function onInput(evt:TextEvent):void {
	if (phoneField.length==3 || phoneField.length==7) {
		phoneField.appendText("-");
		var leng:int=phoneField.text.length;
		phoneField.setSelection(leng, leng);
	}
}

Quick way to make sure text input is formatted like a phone number.

perlinNoise()

var canvas:BitmapData = new BitmapData(400,400,false, 0x000000);
addChild(new Bitmap(canvas));

addEventListener(Event.ENTER_FRAME, onLoop);
function onLoop(evt:Event):void {
  canvas.perlinNoise(200,200, 2, 1, true, false,0, true, 
                              [new Point(mouseX, mouseY),
                              new Point(-mouseX, -mouseY)]);
																				    
}

There area few snippets on the way that involve perlin noise. Starting here with something simple. This creates 2 octave perlin noise and moves each octave based on the mouse location.

Perlin noise was invented by Ken Perlin.

drawPath() Circle Segment

drawPath() is flash 10 player only

[SWF(width=400,height=400,backgroundColor=0xEFEFEF,frameRate=30)]

const TWO_PI:Number = Math.PI * 2;

var resolution:Number = 50;
var step:Number = TWO_PI / resolution;
var maxIndex:int = 0;

var coords:Vector.<Number> = new Vector.<Number>();
var drawCommands:Vector.<int> = new Vector.<int>();

// populate vectors
for (var i:Number = 0; i < TWO_PI + step; i += step){
	coords.push(100 * Math.cos(i));
	coords.push(100 * Math.sin(i));
	drawCommands.push(GraphicsPathCommand.LINE_TO);
}
 
var circleSegment:Shape = new Shape();
circleSegment.x = circleSegment.y = 200;
addChild(circleSegment);

addEventListener(Event.ENTER_FRAME, onLoop);
function onLoop(evt:Event):void {
	with (circleSegment.graphics) {
		clear();
		beginFill(0x000000);
		
		// count by two, up to coords.length (drawCommands is exactly half the length of coords)
		maxIndex =  Math.ceil((mouseX / stage.stageWidth)  * drawCommands.length) * 2;

        drawPath(drawCommands, coords.slice(0, maxIndex));
	}
}

The new additions to the Drawing API are great. This is just a quick test done with drawPath() to create a circle segment – this technique could be used to draw a pie chart.

The old way would have required lots of calls to the Graphics.lineTo() method. Take a look:


const TWO_PI:Number = Math.PI * 2;

var resolution:Number = 50;
var step:Number = TWO_PI / resolution;
var maxAngle:Number;

var circleSegment:Shape = new Shape();
circleSegment.x = circleSegment.y = 200;
addChild(circleSegment);

addEventListener(Event.ENTER_FRAME, onLoop);
function onLoop(evt:Event):void {
	with (circleSegment.graphics) {
		clear();
		beginFill(0x000000);
		
		// count up to (TWO_PI + step), we add step to close the circle
		maxAngle =  (TWO_PI + step) *  (mouseX / stage.stageWidth);

		for (var i:Number = 0; i < maxAngle; i += step) {
			var xp:Number = 100 * Math.cos(i);
			var yp:Number = 100 * Math.sin(i);
			lineTo(xp, yp);
		}
	}
}

If your interested in learning more about the FP10 Drawing API features, you can read more here.

Isometric Box

stage.frameRate = 30;

for (var i:int = 0; i<100; i++){
    makeBoxSegment(200, 200 - i, i * 2);
}

function makeBoxSegment(xp:Number, yp:Number, col:uint):Sprite {
	var isoBox:Sprite = Sprite(addChild(new Sprite()));
	with (isoBox) scaleY = .5, y = yp, x = xp;
	var box:Shape = Shape(isoBox.addChild(new Shape()));
	box.rotation = 45;
	with (box.graphics) beginFill(col), drawRect(-50,-50,100,100);
	isoBox.addEventListener(Event.ENTER_FRAME, onRotate);
	return isoBox;
}

function onRotate(evt:Event):void {
	evt.currentTarget.getChildAt(0).rotation = mouseX;
}

An isometric box that rotates with the mouseX.

Multiple Keys

var key:Object = new Object();
stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyPressed);
stage.addEventListener(KeyboardEvent.KEY_UP, onKeyReleased);
function onKeyPressed(evt:KeyboardEvent):void {
	key[evt.keyCode] = true;
	key.keyCode = evt.keyCode;
}
function onKeyReleased(evt:KeyboardEvent):void {
	key[evt.keyCode] = false
}

// example

addEventListener(Event.ENTER_FRAME, onLoop);
function onLoop(evt:Event):void {
	
	//trace(key.keyCode);
	 
	if (key[Keyboard.LEFT]){
		trace("left");
	}
	
	if (key[Keyboard.RIGHT]){
		trace("right");
	}
	
	// keys #1, #2 and #3 are down
	if (key[49] && key[50] && key[51]){
		trace("one two thee");
	}
	
	// keys #6, #7, #8 and #9 keys are down
	if (key[54] && key[55] && key[56] && key[57]){
		trace("six seven eight nine");
	}
}

The first 10 lines of code make up this snippet. This is an easy way to keep track of multiple key presses. For games, this is the only key technique I use … wrapped up in a Singleton.