Browse the notebook

Category: dynamic

Dynamic Graphics and Function.apply()

var cmds:Array = [["lineStyle", 0, 0xFF0000], ["drawCircle",100, 100, 50], ["drawRect", 50, 50, 100, 100]];
cmds.push(["drawCircle", 100, 100, 70]);
cmds.push(["beginFill",  0x555555]);
cmds.push(["drawRoundRect", 80, 80, 40, 40, 10, 10]);
cmds.push(["endFill"]);

render(cmds);

function render(p:Array):void {
	for (var i:int = 0; i<p.length; i++) {
		graphics[p[i][0]].apply(graphics,p[i].splice(1));
	}
}

The above creates a function called render() that takes a 2D array of Graphics class methods and then runs them. This is a very interesting technique, specifically if you’d like to write Graphics class method calls in an XML or txt file and then have them run on a given DisplayObject in flash.

I’ve been thinking about the best way to do this for awhile… I started off doing something very convoluted and then realized that I could use Function.apply()….

Tomorrow I’ll post a snippet showing how to use this function in conjunction with XML.

Read snippet: Dynamic Graphics and Function.apply()

Snippet Template (imports)

package {
	import adobe.utils.*;
	import flash.accessibility.*;
	import flash.display.*;
    import flash.errors.*;
    import flash.events.*;
    import flash.external.*;
    import flash.filters.*;
    import flash.geom.*;
    import flash.media.*;
    import flash.net.*;
    import flash.printing.*;
    import flash.profiler.*;
    import flash.sampler.*;
    import flash.system.*;
    import flash.text.*;
    import flash.ui.*;
    import flash.utils.*;
    import flash.xml.*;
    
	dynamic public class Snippet extends MovieClip {
		public function Snippet() {
			 // paste your snippet here (functions and all)
		}
	}
}

This snippet imports all flash packages and is dynamic… you can copy actionsnippet code into the constructor of this file if you use Flex, FlashDevelop, TextMate etc… I tested it with a bunch of snippets and it seems to work nicely.

When I first teach classes in AS3 this is the template I use:

package{
	import flash.display.*;
	import flash.events.*;
	 
	public class Main extends Sprite{
		// etc...
	}
}

Display and events cover a lot of ground….. next one I find myself adding is flash.geom, followed by flash.net… I’d say those are my top 4 most frequently used packages…. I do lots of text layout in the Flash IDE, otherwise flash.text would be in there….

Read snippet: Snippet Template (imports)

nesting(function(calls()))

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

for (var i:int = 0; i<10; i++){
       // draggable ellipse
	var dot:Sprite = drag(createSprite("Ellipse",  -10, -10, 20, 20));
	dot.x = Math.random() * stage.stageWidth ;
	dot.y = Math.random() * stage.stageHeight ;
}

for (i = 0; i<10; i++){
  
      var box:Sprite = drag(spin(createSprite("Rect", -20, -20, 40, 40, 0xFF0000), Math.random()*5 + 1));
	box.x = Math.random() * stage.stageWidth ;
	box.y = Math.random() * stage.stageHeight ;
}


 // createSprite can create ellipses or rectangles
function createSprite(shape:String, xp:Number, yp:Number, w:Number, h:Number, col:uint=0x444444):Sprite {
	var s:Sprite = new Sprite();
	s.graphics.beginFill(col);
	// trick from a previous post
	s.graphics["draw" + shape](xp, yp, w, h);
	addChild(s);
	return s;
}

// drag and spin add listeners to an untyped target and return that target for easy function nesting
function drag(target:*):*{
	target.addEventListener(MouseEvent.MOUSE_DOWN, function(evt:MouseEvent){ evt.currentTarget.startDrag(); });
	return target;
}

function spin(target:*, speed:Number):*{
	target.addEventListener(Event.ENTER_FRAME, function(evt:Event){ evt.currentTarget.rotation+=speed; });
	return target;
}

stage.addEventListener(MouseEvent.MOUSE_UP, function(){ stopDrag() });

The above will create some draggable circles and some rotating draggable rects… but that’s not really the point….

When prototyping and just playing around I write functions that take an Object as an argument, alter that Object in some way and pass that some Object out as a return value…. this makes it so I can write things like this:

drag(spin(createSprite("Rect", -20, -20, 40, 40, 0xFF0000), Math.random()*5 + 1));

Readability can be a problem so… consider that before using this for anything…

Read snippet: nesting(function(calls()))

Dynamic Vars Dictionary


var vars:Dictionary = new Dictionary();

var sp:Sprite = new Sprite();

// associate variables with a sprite (or any non-dynamic class)
vars[sp] = {posX:100, posY:100, velX:1, velY:1};

// read
trace(vars[sp].posX);

I’ve heard people mention that they wish the sprite class were dynamic… meaning they wish they could add methods and properties to a Sprite instance at runtime. There’s no way I know of to do this, however… the dictionary class can be used to associate variables with any non-dynamic class instance… as it does in this the above example.

The dictionary class is similar to an associative array except that instead of using strings for keys, dictionaries use object instances.

Read snippet: Dynamic Vars Dictionary

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….

Read snippet: Object.prototype Crap

Mini Tween Engine

var box:MovieClip = new MovieClip();
box.graphics.beginFill(0xFF0000);
box.graphics.drawRect(-25,-25,50,50);
addChild(box);

stage.addEventListener(MouseEvent.CLICK, onStageDown);
function onStageDown(evt:MouseEvent):void{
	moveTo(box, "x", 300, 2, Back.easeOut);
	moveTo(box, "y", 200, 2, Back.easeOut);
	moveTo(box, "scaleX", 2, 2, Back.easeOut);
	moveTo(box, "rotation", 180, 2, Quartic.easeOut, onDone);
	stage.removeEventListener(MouseEvent.CLICK, onStageDown);
}
					 
function onDone():void {
	moveTo(box, "x", 120, 2, Back.easeIn);
}

//
// -- TWEEN ENGINE
//
import fl.motion.easing.*;

// movieClip to tween, property to tween, final value for the property, duration of tween,
// ease type, complete callback function
function moveTo(mc:MovieClip, prop:String, dest:Number, duration:Number, ease=null, 
				           completeFunction:Function=null):void {
	if (ease == null) {
		ease = Quartic.easeOut;
	}
	// use the property to make all var names unique
	mc["begin" + prop] = mc[prop];
	mc["change" + prop] =  dest - mc[prop];
	mc["time" + prop] = 0;
	mc["startTime" + prop] = getTimer();
	mc["duration" + prop] = duration;
	mc["prop"] = prop;
	mc["ease" + prop] = ease;
	mc["complete_" + prop] = completeFunction;
	mc.addEventListener(Event.ENTER_FRAME, makeMotionFunction(mc, prop));
}

function makeMotionFunction(mc:MovieClip, prop:String):Function {
	return function(evt:Event){
		if (mc["time" +prop] <= mc["duration"+ prop]){ 
		   mc[prop]=mc["ease" + prop](mc["time" + prop], mc["begin" +prop], mc["change"+ prop], mc["duration"+ prop]);
		} else {
			var completeFunction:Function = mc["complete_"+prop];
			if (completeFunction!=null){
			  completeFunction();
			}
			mc.removeEventListener(Event.ENTER_FRAME, arguments.callee);
			// see how long the tween took
		    //trace(mc["time"+prop]);
		}
		   mc["time" + prop] = (getTimer() - mc["startTime" + prop]) / 1000;
	};
}
/*
WARNING: This code was written for fun. Use at your own risk.
*/

This code uses a ~35 line tweening engine. I wrote this for fun a few weeks back. It works by creating dynamic variables on the MovieClip that it tweens. The dynamic variables and the square bracket syntax cause it to be pretty slow. Definitely not a substitute for a real tweening engine… like TweenLite.

I wouldn’t recommend using this for anything other than playing around. See warning page for more info.

Read snippet: Mini Tween Engine