Browse the notebook

Tag: flash

MovieClip.prototype

MovieClip.prototype.tint = function(col:uint):void {
	var ct:ColorTransform = transform.colorTransform;
	ct.color = col;
	this.transform.colorTransform = ct;
}

var circle:MovieClip = MovieClip(addChild(new MovieClip()));
with (circle.graphics) {
	beginFill(0x123455);
	drawCircle(0,0,50);
	x = 100;
	y = 100;
}

circle.tint(0xFF0000);

When AS3 first came out I didn’t realize that prototype was still around…. This adds a function called tint() to all MovieClips. You should extend MovieClip instead of using this method…. but it’s interesting to see that it’s still around. There’s an explanation of prototype and the AS3 namespace here.

Read snippet: MovieClip.prototype

10,000 Transparent Sprites

stage.frameRate = 30;

var imageNum:int = 10000;
var point:Point = new Point(0,0);
var s:Sprite = new Sprite();
s.graphics.beginFill(0xCCCCCC);
s.graphics.lineStyle(0,0x000000);
s.graphics.drawCircle(3,3,3);
s.alpha = .1;

var nested:Sprite = new Sprite();
nested.addChild(s);
var image:BitmapData = new BitmapData(s.width, s.height, true, 0x00000000);
image.draw(nested);

var canvas:BitmapData = new BitmapData(400,400, true, 0xFFFFFFFF);
addChild(new Bitmap(canvas));

var xPos:Array = new Array();
var yPos:Array = new Array();
for (var i:int = 0; i<imageNum; i++) {
	xPos.push(Math.random()*400);
	yPos.push(Math.random()*400);
}

addEventListener(Event.ENTER_FRAME, onLoop);
function onLoop(evt:Event):void {
	canvas.fillRect(new Rectangle(0,0,400,400), 0xFFFFFFFF);
	var div:Number;
	for (var i:int = 0; i<imageNum; i++) {
		div  = (i / 100)+2;
		xPos[i] += (mouseX - xPos[i])/div;
		yPos[i] += (mouseY - yPos[i])/div;
		point.x = xPos[i];
		point.y = yPos[i];
		canvas.copyPixels(image, image.rect, point, null, null, true);
	}
}

This is from my other blog but I figured it was worth posting here. It draws 10’000 transparent circles that each follow the mouse at different speeds. This is achieved using copyPixels().

Read snippet: 10,000 Transparent Sprites

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

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");
}
Read snippet: KeyCode Variables

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";
Read snippet: const

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.

Read snippet: Sine Cosine Walk