Latest snippets

Parallax Based on Y

[SWF(backgroundColor=0x000000, frameRate=30)]

var elements:Array = new Array();
for (var i:int = 0; i<200; i++){
	var c:MovieClip= MovieClip(addChild(new MovieClip()));
	c.x = Math.random()*(stage.stageWidth + 100) - 50;
	c.y = Math.random()*stage.stageHeight;
	with(c.graphics) lineStyle(2, 0xFFFFFF,3), drawCircle(0,0,2 + c.y / 20);
	c.startX = c.x;
	elements.push(c);
}

var offset:Number = 0;
var t:Number = 0;

addEventListener(Event.ENTER_FRAME, onLoop);
function onLoop(evt:Event):void {
	t+=.1;
	offset = 200 * Math.cos(t);
	for (var i:int = 0; i<elements.length; i++){
	   elements[i].x = elements[i].startX + offset / ((stage.stageWidth - elements[i].y) / 80);
	}
}

I wrote this snippet originally to automatically add parallax motion to a bunch of quick drawings I did within the flash IDE. Each movieClip in the elements array is moved from left to right based on it’s y position. Clips with a higher y value will oscillate more from left to right than clips with lower y values.

Here is the original drawing I used this on.

And here is what the above snippet will create.

Animate Graphics.lineTo()

// line thickness, line color, start point, end point, divisor, callback
function animateLineTo( thick:Number, col:uint, sp:Point, ep:Point, div:Number=4, callback:Function=null):void {
	 var s:Shape  = Shape(addChild(new Shape()));
	 var ap:Point = sp.clone();
	 div = Math.max(2, div);
	 setTimeout(runLineAnimation, 1000/stage.frameRate, s.graphics , thick , col , sp , ep , ap, div, callback);
}

function runLineAnimation(g:Graphics , thick:Number, col:uint, sp:Point, ep:Point, ap:Point, div:Number, callback:Function):void {
	 ap.x += (ep.x - ap.x) / div;
	 ap.y += (ep.y - ap.y) / div;
	  with(g){
		clear();
		lineStyle(thick, col);
		moveTo(sp.x, sp.y);
		lineTo(ap.x, ap.y);
	  }
	   if (Math.abs(ap.x - ep.x) < 1 && Math.abs(ap.y- ep.y)  < 1){
		   // done
		   if (callback!=null){
			   callback();   
		   }
	   }else{
		    setTimeout(runLineAnimation, 1000/stage.frameRate, g , thick , col , sp , ep , ap, div, callback);
	   }
}
//
// test out the animateLineTo function:
//
var a:Point = new Point(100,100);
var b:Point = new Point(150, 200);
var c:Point = new Point(300, 190);
var d:Point = new Point(280, 90)

animateLineTo(0, 0xFF0000, a, b, 4, line2);

function line2():void{
	animateLineTo(0, 0xFF0000, b, c, 4, line3);
}

function line3():void{
	animateLineTo(0, 0xFF0000, c, d, 4, line4);
}

function line4():void{
	animateLineTo(0, 0xFF0000, d, a, 4);
}

The above demos a function called animateLineTo() that will draw a line using zeno’s paradox.

There are a couple weird/interesting tricks going on here. I’m using setTimeout() over and over rathaer than using setInterval(). This makes it so I don’t need to store an interval id. I’m also using a delay of 1000/stage.frameRate, this attempts to cause the setTimeout() to run at the same frequency as an enter frame would. This is important because having a setTimeout()/setInterval() that is doing animation and attempting to run more frequently than the framerate can cause problems and is a waste of cpu power.

This snippet was spurned by a student question about how to animate a Graphics.lineTo() from point A to point B. Here is the original snippet, which is easier to read and more bare bones:

var p0:Point = new Point(100,100);
var p1:Point = new Point(400,200);
var dp:Point = new Point(p0.x,p0.y);

var s:Sprite = Sprite(addChild(new Sprite()));

addEventListener(Event.ENTER_FRAME, onLoop);
function onLoop(evt:Event):void {
	s.graphics.clear()
	s.graphics.lineStyle(0,0x000000);
	s.graphics.moveTo(p0.x, p0.y);
	s.graphics.lineTo(dp.x, dp.y);
	dp.x += (p1.x - dp.x) / 4;
	dp.y += (p1.y - dp.y) / 4;
}

Readable Conditionals

// NOTE: this code won't do anything in you're timline....

// do you do this?

if (ball.x < 0 || ball.y < 0 || ball.x > stage.stageWidth || ball.y > stage.stageHeight){
       // cause ball to explode
}

// or this?

if (isAtStageEdge(ball)){
       // cause ball to explode
}

function isAtStageEdge(mc:MovieClip):Boolean{
   return (mc.x < 0 || mc.y < 0 || mc.x > stage.stageWidth || mc.y > stage.stageHeight);
}

This is pretty standard stuff, but it can increase code readability especially for complex conditionals.

I also do this if I find myself repeating an a semi-complex if statement in two or more places.

If I’m just brainstorming I probably won’t bother, but on real projects it helps keep code readable.

String.fromCharCode()

[SWF(height = 950, width=1000)]
var txt:TextField;
var num:int = 0;
for (var i:int = 0; i<761; i++){
	if (i % 76 == 0){
		 makeTxt(num);
		 num++;
	}
	if (i < 0x21){
		txt.appendText("-n");
	}else{
	    txt.appendText(String.fromCharCode(i) + " = " +  i + "n");
	}
}
function makeTxt(num:Number):void{
	 txt= TextField(addChild(new TextField()));
     txt.x = 10 + num * 100;
     txt.y = 10;
     txt.height = 930;
     txt.text = "";
}

This will draw a few columns of char codes.

String.localeCompare()

var letterA:String = "a";
var letterZ:String = "z";

trace(letterA.localeCompare(letterZ));
trace(letterZ.localeCompare(letterA));
/*
outputs
-25
25
*/

String.localeCompare() calculates the sorting order between two Strings….

Random Sort

function randomize(a:*, b:*):int{
       return Math.round(Math.random()*8) - 4;
}

var i:int;
var fruits:Array;

trace("Math.random()");
for (i = 0; i<4; i++){
  // reset fruits array:
  fruits = ["apple", "grape","pear","cherry"];
  fruits.sort(randomize);
  trace(fruits);
}


// seeds
var s1:Number= 0xFF00FF;
var s2:Number = 0xCCCCCC;
var s3:Number= 0xFF00F0;

function tRandomize(a:*, b:*):int{
       return Math.round(rand()*8) - 4;
}

trace("nTausworthe rand()");
for (i= 0; i<4; i++){
  fruits = ["apple", "grape","pear","cherry"];
  fruits.sort(tRandomize);
  trace(fruits);
}
// from www.ams.org/mcom/1996-65-213/S0025-5718-96-00696-5/S0025-5718-96-00696-5.pdf
function rand():Number {
	s1=((s1&4294967294)<<12)^(((s1<<13)^s1)>>19);
	s2=((s2&4294967288)<<4)^(((s2<<2)^s2)>>25);
	s3=((s3&4294967280)<<17)^(((s3<<3)^s3)>>11);
	var r:Number = (s1^s2^s3) * 2.3283064365e-10;
	r = (r<0) ? r+=1 : r;
	return r;
}

/*
outputs:
Math.random()
grape,apple,pear,cherry
pear,cherry,apple,grape
grape,apple,pear,cherry
grape,apple,cherry,pear

Tausworthe rand()
apple,grape,pear,cherry
cherry,grape,pear,apple
grape,apple,cherry,pear
grape,pear,apple,cherry
*/

The above shows how to randomly sort or shuffle an array. This is useful in games. To achieve this I made use of the compareFunction argument of Array.sort(). Most sorting algorithms go through the array and compare values until the desired sort order is achieved. The compareFunction argument is a function that takes two values a and b and returns an integer that is negative positive or zero… see this info from the docs:
* A negative return value specifies that A appears before B in the sorted sequence.
* A return value of 0 specifies that A and B have the same sort order.
* A positive return value specifies that A appears after B in the sorted sequence.

So in the case of a randomizing an array you simply need to return a random int -1, 0 or 1. This is what I’ve done in the past (Math.round()*2) -1) … but when I was writing this snippet it seemed like 0 caused less variation in the output of the array so I made the range from -4 to 4 instead. This could have just been my imagination, but it seems like having less chance of a zero caused the arrays to be a bit more shuffled.

The reason I also included a version that uses Tausworthe is because of the easy seeding. In some cases you may want to use seeded randomness to sort an array.

UPDATE:
Was digging around about this and found a much faster method for randomizing arrays… not a big deal if you have small arrays, but if you need to randomize 1000’s of values this method is much faster than using Array.sort()

String.indexOf()

var words:String = "one two three four five";

trace("two: ", words.indexOf("two"));

var letters:String = "abcd";

trace("d: ",letters.indexOf("d"));

trace("z: ",letters.indexOf("z"));

/*
outputs:
two:  4
d:  3
z:  -1
*/

indexOf() searches a string for another string and returns an index… in line 3 above, I search the words string for the smaller string “two” and indexOf() gives me the index of the letter “t”. If indexOf() doesn’t find anything it will return -1 (as in the case of line 9).

I seem to recall using this in some unexpected places. I’ll see if I can dig up an example over the next few days.

Zig Zag Binary ix2 & i/2

var txt:TextField = TextField(addChild(new TextField()));
txt.text = "";
txt.width = 190;
txt.height = 400;
txt.multiline = true;

var count:int = 1;
function render():void{
	var line = int(count).toString(2);
	while(line.length < 31){
		line = "0" + line;
	}
    txt.appendText(line + "n");
	txt.scrollV= txt.maxScrollV;
}

addEventListener(Event.ENTER_FRAME, onCountUp);
function onCountUp(evt:Event):void {
	count *= 2;
	render();
	if (count ==0x40000000){
		removeEventListener(Event.ENTER_FRAME, onCountUp);
		addEventListener(Event.ENTER_FRAME, onCountDown);
	}
}
function onCountDown(evt:Event):void {
	count /= 2;
	render();
	if (count ==1){
		addEventListener(Event.ENTER_FRAME, onCountUp);
		removeEventListener(Event.ENTER_FRAME, onCountDown);
	}
}

The above animates a zig zag pattern in a TextField.

N to the power of N (with strings)

var input:String =  "a, b, c";

var words:Array = input.split(", ");
var max:String = "";
var maxD:String =  (words.length - 1).toString();
for (var i:int = 0; i<words.length; i++){
	max += maxD;
}
var maxInt:int = parseInt(max,words.length);

for(i = 0; i<=maxInt; i++){
	 var indices:String = i.toString(words.length);
	 var r:String = "";
	 var k:int=0;
	 for (var j:int = 0; j<indices.length; j++){
		 r += words[parseInt(indices.charAt(j))] +" ";
		 k++;
	 }
	 while(k < words.length) {
		r = words[0] +" "+ r;
		k++;
	 }
	trace(r);
}
trace(i, " variations");

Like many things on this site, I coded this rather quickly and it can probably be cleaned up…

Setting the input variable of the above snippet to “a, b” will output:

a a
a b
b a
b b
4 variations

Setting the input to “a, b, c” will output:

a a a
a a b
a a c
a b a
a b b
a b c
a c a
a c b
a c c
b a a
b a b
b a c
b b a
b b b
b b c
b c a
b c b
b c c
c a a
c a b
c a c
c b a
c b b
c b c
c c a
c c b
c c c
27 variations

I created this to work with words… inputs like “bread, breath, blobs, backwards”. Be careful because you can quickly get millions of outputs:

1 to the power of 1 is 1
2 to the power of 2 is 4
3 to the power of 3 is 27
4 to the power of 4 is 256
5 to the power of 5 is 3125
6 to the power of 6 is 46,656
7 to the power of 7 is 823,543
8 to the power of 8 is 16,777,216
etc…

Tweetcoding

g=graphics;
mt=g.moveTo;
lt=g.lineTo;
ls=g.lineStyle;
m=Math;
r=m.random;
s=m.sin;
i=0;
o={};
function f(e){
	s=150,x=y=s,z=-s,c=(!i)?addChild(new Bitmap(new BitmapData(s,s))).bitmapData:c;while(i<22500)i++,c.setPixel(i%s,i/s,(i%s|i/s)*mouseX);i=1;
}
addEventListener("enterFrame",f);

Have to link to this very fun new contest:

http://tweetcoding.machine501.com/

http://gskinner.com/playpen/tweetcoding.html

I may just have to get a twitter account…