Browse the notebook

Month: November 2008

Loader, Centering, Smoothing

var image:Loader = new Loader();
image.load(new URLRequest("http://www.shapevent.com/sketchbook/wp-content/uploads/avalanche.jpg"));
image.x = stage.stageWidth / 2;
image.y = stage.stageHeight / 2;
addChild(image);

image.contentLoaderInfo.addEventListener(Event.COMPLETE, onComplete);
function onComplete(evt:Event):void {
	
	// CENTER THE IMAGE
	image.content.x = -image.content.width / 2;
	image.content.y = -image.content.height / 2;
	
	// BITMAP SMOOTHING
	Bitmap(image.content).smoothing = true;
	image.contentLoaderInfo.removeEventListener(Event.COMPLETE, onComplete);
}


// scale the image with the mouse to demonstrate smoothing and scaling from the center
addEventListener(Event.ENTER_FRAME, onLoop);
function onLoop(evt:Event):void {
	image.scaleX = image.scaleY = mouseX / stage.stageWidth;
}

This is really two snippets combined. How to scale the content of a Loader from the center:

// CENTER THE IMAGE
image.content.x = -image.content.width / 2;
image.content.y = -image.content.height / 2;

and how to smooth a jpg, png etc… that has been loaded dynamically into your swf:

// BITMAP SMOOTHING
Bitmap(image.content).smoothing = true;
Read snippet: Loader, Centering, Smoothing

Reset Registration Point


// display object target, value - "center" or "upperLeft"
function setRegistration(dsp:DisplayObjectContainer, v:String):void {
	var i:int;
	var child:DisplayObject;
	var b:Rectangle=getBounds(dsp);
	for (i = 0; i < dsp.numChildren; i++) {
		child=dsp.getChildAt(i);
		child.x+=b.x*-1;
		child.y+=b.y*-1;
	}
	if (v=="center") {
		dsp.x+=dsp.width/2;
		dsp.y+=dsp.height/2;
		for (i = 0; i < dsp.numChildren; i++) {
			child=dsp.getChildAt(i);
			child.x-=dsp.width/2;
			child.y-=dsp.height/2;
		}
	} else if (v == "upperLeft") {
		if (dsp.parent) {
			b=getBounds(dsp.parent);
			dsp.x=b.left;
			dsp.y=b.top;
		}
	}
}

// example:
// (make a MovieClip and fill it with, text, shapes etc...)

setRegistration(clip, "center");
// registration(clip, "upperLeft");

addEventListener(Event.ENTER_FRAME, onLoop);
function onLoop(evt:Event):void {
	clip.rotation+=1;
}

Teaching beginner flash… I’ve noticed people always get confused about the registration point. They think they should be able to move it with the IDE or ActionScript. I always say “You can’t change the registration point, you can only change the position of graphical elements in relationship to it.” Anyway, as a sort of joke one day after class I wrote the above function… it changes the registration of any DisplayObjectContainer to either “center” or “upperLeft”.

To test this code out, fill a MovieClip with a bunch of different things (text, graphics, scribbles)… give it a strange registration point and then run the above code on it. You’ll be able to tell that the registration has changed by the way the clip rotates. Although I haven’t been able to break this function, I think it’s possible that it doesn’t work under all circumstances.

Using reparenting is a more elegant solution to this issue. Maybe I’ll post that in the next couple days.

Read snippet: Reset Registration Point

Skew DisplayObject

var box:Shape = Shape(addChild(new Shape()));
with (box.graphics) beginFill(0x006666), drawRect(0,0,50,50);
box.x = box.y = 100;

addEventListener(Event.ENTER_FRAME, onLoop);

function onLoop(evt:Event):void {
	
	var m:Matrix = box.transform.matrix;
	// skew on the X
	m.c = (mouseX - stage.stageWidth / 2 ) / stage.stageWidth;
	
	// skew on the Y
	// m.b = (mouseX - stage.stageWidth / 2 ) / stage.stageWidth 
	
	box.transform.matrix = m
}

This skews a box Shape using the c and b properties of the transformation matrix. Note that these values don’t match those in the IDE’s transform window. This is good further reading if your interested in this topic.

Read snippet: Skew DisplayObject

Basic Tint Function

// display object, red (0-255), green, blue, amount (0-1)
function tint(dsp:DisplayObject, r:Number, g:Number, b:Number, amount:Number=1):void {
	if (amount != 1) {
		r *= amount;
		g *= amount;
		b *= amount;
	}
	amount = 1-amount;
	var ct:ColorTransform = transform.colorTransform;
	ct.redOffset = r;
	ct.redMultiplier = amount;
	ct.greenOffset = g;
	ct.greenMultiplier = amount;
	ct.blueOffset = b;
	ct.blueMultiplier = amount;
	dsp.transform.colorTransform = ct;
}

// test out the tint function on a circle with a stroke:
var circle:Shape = Shape(addChild(new Shape()));
with (circle.graphics) {
	lineStyle(5, 0x339999);
	beginFill(0x003333);
	drawCircle(0,0,50);
	x = 100;
	y = 100;
}

// tint the circle 50% green
tint(circle, 0, 255, 0, .5);

The ColorTransform object is a little confusing with its “redMultiplier, redOffset, greenMultiplier etc…” properties. Once you understand them it’s not a big deal, but I still find them a bit cumbersome. So when I just want to tint a clip similar to the way you might tint a clip in the IDE… I use this tint function. Rather than taking a hexidecimal number it takes values for red, green and blue (0-255) – and an amount argument (0-1).

Read snippet: Basic Tint Function

Mouse Velocity

var velocityInfo:TextField = new TextField();
velocityInfo.x = 20;
velocityInfo.y = 20;
addChild(velocityInfo);

var prevX:Number = mouseX;
var prevY:Number = mouseY;
var velX:Number = 0;
var velY:Number = 0;

addEventListener(Event.ENTER_FRAME, onLoop);

function onLoop(evt:Event):void {
	 
	 velX = mouseX - prevX;
	 velY = mouseY - prevY;
	 
	 velocityInfo.text = velX + ", " + velY
	 
	 prevX = mouseX;
	 prevY = mouseY;
}

Wrote this in response to a question from one of my students. The next step is to use velX and velY to push objects around the screen.

Read snippet: Mouse Velocity

Animate Along a Path

stage.frameRate = 30;
var pencil:Shape = new Shape();
addChild(pencil);

var index:int = 0;
var points:Array = new Array();
var circle:Shape = new Shape();
circle.graphics.beginFill(0x000000);
circle.graphics.drawCircle(0,0, 5);
addChild(circle);

stage.addEventListener(MouseEvent.MOUSE_DOWN, onDown);
stage.addEventListener(MouseEvent.MOUSE_UP, onUp);

circle.addEventListener(Event.ENTER_FRAME, onMoveCircle);

function onDown(evt:MouseEvent):void {
	pencil.graphics.lineStyle(0,0x000000);
	pencil.graphics.moveTo(mouseX, mouseY);
	stage.addEventListener(MouseEvent.MOUSE_MOVE, onDraw);
}

function onUp(evt:MouseEvent):void {
	stage.removeEventListener(MouseEvent.MOUSE_MOVE, onDraw);
}

function onDraw(evt:Event):void {
	pencil.graphics.lineTo(mouseX, mouseY);
	points.push(new Point(mouseX, mouseY));
}

function onMoveCircle(evt:Event):void {
	if (points.length>0) {
		circle.x += (points[index].x - circle.x) / 4;
		circle.y += (points[index].y - circle.y) / 4;
		index++;
		if (index==points.length) {
			index=0;
		}
	}
}

Wrote this in response to a student question. It causes a circle shape to animate along lines drawn by the user.

Read snippet: Animate Along a Path

new Sprite() One-liner

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

A way to make a new sprite, add it to the display list and store a reference to it.

Figured this out on my own… but have since seen it around on a few flash blogs here and there… thought it deserved a post.

Read snippet: new Sprite() One-liner

Alphabet with Base36 and Binary

var canvas:BitmapData=new BitmapData(280,100,false,0xefefef);
addChild(new Bitmap(canvas));

// pixel alphbet in base36
var alphabet:Array=["", "67erkgi", "e3j6dss", "75rue4u", "c5ltok8", "75s2tji", "75s2tjk", "75rugj2", "95yfnf6", "21blls4", "10nt5xo", "973it1u", "85aef4u", "59lu6nl", "cnz0hbn", "67ej51o", "67eq49c", "67ej53e", "67eq7gy", "66978m4", "6ywdqpw", "95y780c", "53b00as", "8nmdpyi", "5374thm", "53avnus", "6xsfdam"];

function drawBase36(num:String, xp:int, yp:int):void {
	// convert base36 to binary
	num=parseInt(num,36).toString(2);
	while (num.length < 35) {
		num="0"+num;
	}
	// draw letter
	for (var i:int= 0; i<35; i++) {
		if (num.charAt(i)=="1") {
			canvas.setPixel(i % 5 + xp, int(i / 5) + yp, 0x000000);
		}
	}
}

// draw the entire alphabet
for (var i:int = 0; i<alphabet.length; i++) {
	drawBase36(alphabet[i], i * 10,10);
}

// draw some words
var words:Array=[0,1,3,20,9,15,14,19,14,9,16,16,5,20,0,9,19,0,3,15,4,5];
for (i = 0; i<words.length; i++) {
	drawBase36(alphabet[words[i]], i * 10,30);
}

I had lots of fun writing this. If you run it in your timeline it will draw this:


… along with the message stored in this array [0,1,3,20,9,15,14,19,14,9,16,16,5,20,0,9,19,0,3,15,4,5].

Binary can be used for representing small images. For every 0 draw white for every 1 draw black. So when the base36 numbers are converted to binary, the 1’s and 0’s are used to draw each letter.

An interesting side note is that counting in binary to some very high numbers will enumerate all possible two color images at a given size. There are tons of projects related to this… here is one I found with a quick google search: every icon

I also found the wikipedia entry on base36 to be interesting. Apparently base36 can be called hexatridecimal, sexatrigesimal, hexatrigesimal or alphadecimal.

Read snippet: Alphabet with Base36 and Binary

2D Z-Sort

var shapes:Array = new Array();

for (var i:int = 0; i<300; i++){
	var s:Shape = new Shape();
	s.x = Math.random()* stage.stageWidth;
	s.y = Math.random()* stage.stageHeight;
	s.graphics.lineStyle(0,0x000000);
	s.graphics.beginFill(0xCCCCCC);
	s.graphics.drawCircle(0,0, Math.random()*s.y / 5);
	shapes.push(s);
}

// comment this out to remove sorting
shapes.sortOn("width", Array.NUMERIC);

for (i = 0; i<shapes.length; i++){
	addChild(shapes[i]);
}

This uses Array.sortOn() to do some basic z-sorting based on the width property of some circle shapes.

Read snippet: 2D Z-Sort

Set Multiple Properties

// set multiple properties of an Object 
function setProps(o:*, props:Object):void{
	for (var key:String in props){
		 o[key] = props[key];
	}
}

// example: 

var s:Sprite = new Sprite();
s.graphics.beginFill(0);
s.graphics.drawRect(0,0,10,10);
addChild(s);

// set some properties
setProps(s, {x:100, y:100, scaleX:2, scaleY:2, rotation:45});

This was inspired by tweening engines like TweenLite.

Basically the same thing using a with statement:

with(s) x = 100, y = 100, scaleX = 2, scaleY = 2, rotation = 45;
Read snippet: Set Multiple Properties