Latest snippets

setPixel() Cubic Bezier

var canvas:BitmapData=new BitmapData(280,280,false,0x000000);
addChild(new Bitmap(canvas, PixelSnapping.AUTO, true));

var color:uint;

// anchor x1, anchor y1, 
// control-handle x2, control-handle y2, 
// anchor x3, anchor y3, control-handle x4, 
// control-handle y4, [resolution incremental value between 0-1]
function cubicBezier(x1:Number, y1:Number, x2:Number, y2:Number, 
	                      x3:Number, y3:Number, x4:Number, y4:Number, resolution:Number=.03):void {
	
	var b:Number,pre1:Number,pre2:Number,pre3:Number,pre4:Number;
	for (var a = 0; a < 1; a+=resolution) {
		b=1-a;
		pre1=(a*a*a);
		pre2=3*(a*a)*b;
		pre3=3*a*(b*b);
		pre4=(b*b*b);
		canvas.setPixel(pre1*x1 + pre2*x2 + pre3*x4 + pre4*x3 ,
				         pre1*y1 + pre2*y2 + pre3*y4 + pre4*y3, color);
	}
}

// draw a few

color = 0xFFFFFF;

cubicBezier(100,100, 
                    150, 50, 
                    200, 100, 
                    150, 150);

color = 0xFF0000;

cubicBezier(10,10,
                    150, 10,
                    200, 200, 
                    250, 150,
			    .01);
/*
WARNING: This code was written for fun. Use at your own risk.
*/

This draws cubic bezier curves with setPixel. I’m pretty sure I picked up the original math from somewhere on the processing forums in ’03 or ’04…

Readable Radial Gradient

var size:Number = 400;
var halfSize:Number = size / 2;
var canvas:BitmapData = new BitmapData(size, size,false, 0x000000);
addChild(new Bitmap(canvas, PixelSnapping.AUTO, true));

var rings:Number = 40;
var color:uint, theta:Number, dx:Number, dy:Number;

for (var i:int = 0; i<canvas.width; i++){
	for (var j:int = 0; j<canvas.height; j++){
		// distance from center of canvas to current x, y coord 
		dx = i - halfSize;
		dy = j - halfSize;
		theta = Math.sqrt((dx * dx)+(dy * dy)) * rings;
		color = (100 + 100  * Math.sin(theta * Math.PI/180)) << 16;
		canvas.setPixel(i,  j, color);
	}
}

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

This is the previous post written in a readable way. Draws a radial gradient using pythagorean theorem and sine.

setPixel() Radial Gradient

 // add a BitmapData object to the stage in one line:
addChild(new Bitmap(new BitmapData(200,200,false,0x00000)));

// draw a radial gradient
for (var i:int = 0; i<200; i++) for (var j:int = 0; j<200; j++) 
Bitmap(getChildAt(0)).bitmapData.setPixel( i, j, 100 + 100 * Math.sin(Math.sqrt(Math.pow(i - 100, 2)+Math.pow(j - 100, 2)) * 40 * Math.PI/180) << 16 );

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

Next I’ll post a readable version, just wanted to see how compact I could get this…

This was inspired by all the pixel bender stuff that I’ve seen. I did the same thing with setVector() – will post about setVector() in the future.

Quick Alphabet Array

var alphabet:Array = ("abcdefghijklmnopqrstuvwxyz").split("");
trace("this is the letter b...", alphabet[1]);
trace(alphabet);
/* outputs:
this is the letter b... b
a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z
*/

This is an easy way to create an array of the alphabet. It’s easier to type than:

var alphabet:Array = ["a","b","c".... etc];

Function Returns a Function


appendExclamation("actionsnippit")("dot")("com")("is")("live");

function appendExclamation(str:String):Function{
  trace(str + "! ");
  return appendExclamation;
}

/* outputs:
actionsnippit!
dot!
com!
is!
live!
*/

This technique allows you to call a function more than once on one line. I first saw this used in the source files from a talk at flashcoders ny… I didn’t attend the talk, but stumbled on this interesting blog post awhile back http://www.flashcodersny.org/wordpress/?p=166.

This is a fun technique to use, I’ve found some unusual uses for it already… some of which you’ll see in later posts….

Sine Cosine Walk

stage.frameRate = 30;
var footA:MovieClip = makeFoot(0);
var footB:MovieClip = makeFoot(Math.PI);

addEventListener(Event.ENTER_FRAME, onLoop);
function onLoop(evt:Event):void {
	 graphics.clear();
	 graphics.lineStyle(0,0x000000);
	 graphics.moveTo(footA.x, footA.y);
	 graphics.curveTo(footA.x + 20, footA.y - 50, 200, 100);
	 graphics.curveTo(footB.x + 20, footB.y - 50, footB.x, footB.y);
}

function makeFoot(startAngle:Number):MovieClip {
	var mc:MovieClip = MovieClip(addChild(new MovieClip()));
	with(mc.graphics) beginFill(0x000000), curveTo(10,-10, 20, 0);
	mc.x = 200;
	mc.y = 200;
	mc.sx = mc.x;
	mc.sy = mc.y;
	mc.t = startAngle;
	mc.r = 50;
	mc.addEventListener(Event.ENTER_FRAME, onRunFoot);
	return mc;
}
function onRunFoot(evt:Event):void {
	var mc:MovieClip = MovieClip(evt.currentTarget);
     with(mc){
		x = sx + r * Math.cos(t); 
		y = Math.min(sy, sy + r * Math.sin(t));
		rotation = sy - y;
		t += .15;
	 }
}

This is a funny looking snippet that creates a very primitive walk cycle with the Graphics class and sine and cosine.

const

const HALF_PI:Number = Math.PI / 2;
const RADS:Number = Math.PI / 180;

trace(HALF_PI);
// convert degrees to radians
trace(180 * RADS);

When I have constant values I often forget to go ahead and make use of the const keyword. I used to do this a good deal when AS3 first came out…. not sure why I stopped doing it. Anyway, hopefully this post will help remind me to use them…

A very common use for them is of course defining event types:

// inside a class
public static const RENDER_COMPLETE:String = "renderComplete";

KeyCode Variables

// create constants for all letter and number keys:
var alphabet:Array = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".split("");
var nums:Array = ["ZERO","ONE","TWO","THREE","FOUR","FIVE","SIX","SEVEN","EIGHT","NINE"];

var key:Object = new Object();
for (var i:int  = 0; i<alphabet.length; i++)
	 key[alphabet[i]] = 65 + i;
	 
for (i = 0; i<nums.length; i++){
	 var code:int = 48 + i;
     key[nums[i]]= code;
	 key[i] = code;
}
	 

// test them out
stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyPressed);
function onKeyPressed(evt:KeyboardEvent):void {
	if (evt.keyCode == key.A){
		trace("the a was pressed");
	}
	if (evt.keyCode == key.B){
		trace("the b was pressed");
	}
	if (evt.keyCode == key.NINE){
		trace("the 9 key was pressed");
	}
	if (evt.keyCode == key["0"]){
		trace("the 0 key was pressed");
	}
}

This is an easy way to store values for alphanumeric keys in variables that make sense… instead of having to do things like this:

// hit the zero key
if (evt.keyCode == 48){
   trace("the zero key was hit");
}