Browse the notebook

Tag: actionscript

Obfuscated Slider

var slider:MovieClip = makeSlider();
slider.addEventListener(Event.CHANGE, function(evt:Event):void{
	trace(evt.currentTarget.percent);									
});

function makeSlider():MovieClip{
	var slider:MovieClip = MovieClip(addChild(new MovieClip()));
	var circle:Sprite = Sprite(slider.addChild(new Sprite()));
	with (circle.graphics) beginFill(0x000000), drawCircle(0,0,10);
	var line:Shape = Shape(slider.addChild(new Shape()));
	with (line.graphics) lineStyle(0,0x000000), lineTo(0, 100);
	slider.x = slider.y = 100;
	circle.addEventListener(MouseEvent.MOUSE_DOWN, function(evt:Event):void{ evt.currentTarget.startDrag(false, new Rectangle(0,0,0,100)), slider.addEventListener(Event.ENTER_FRAME, onChange) });
	var stopIt:Function = function(){ stopDrag(), slider.removeEventListener(Event.ENTER_FRAME, onChange) };
	stage.addEventListener(Event.MOUSE_LEAVE, stopIt);
	stage.addEventListener(MouseEvent.MOUSE_UP, stopIt);
	return slider;
}
function onChange(evt:Event):void { evt.currentTarget.percent = evt.currentTarget.getChildAt(0).y / 100, evt.currentTarget.dispatchEvent(new Event(Event.CHANGE)) }

This is a pretty nasty implementation of a basic slider. Just felt like writing some obfuscated code today… It could probably be made even more confusing with some additional tweaks…

Have a look at the swf over at wonderfl…

Read snippet: Obfuscated Slider

Bounce Ball Inside a Circle

package  {
	import flash.display.Shape;
	import flash.display.Sprite;
	import flash.geom.Point;

	/**
	 * Re: http://board.flashkit.com/board/showthread.php?t=797453
	 * @author makc
	 * @license WTFPLv2
	 */
	public class BouncingBall extends Sprite{
		public function BouncingBall () {
			r = 10;
			ball = new Shape;
			ball.graphics.beginFill (0);
			ball.graphics.drawCircle (0, 0, r);
			addChild (ball);
			v = new Point;
			v.x = Math.random ();
			v.y = Math.random ();
			V = 1 + 20 * Math.random ();
			v.normalize (V);
			R = 200; X = 465 / 2; Y = 465 / 2;
			graphics.lineStyle (0);
			graphics.drawCircle (X, Y, R);
			ball.x = X + 100;
			ball.y = Y - 100;
			addEventListener ("enterFrame", loop);
		}
		private var r:Number;
		private var ball:Shape;
		private var v:Point;
		private var V:Number;
		private var R:Number;
		private var X:Number;
		private var Y:Number;
		private function loop (e:*):void {
			ball.x += v.x;
			ball.y += v.y;
			// R-r vector
			var P:Point = new Point (X - ball.x, Y - ball.y);
			if (P.length > Math.sqrt ((R - r) * (R - r))) {
				// normalize R-r vector
				P.normalize (1);
				// project v onto it
				var vp:Number = v.x * P.x + v.y * P.y;
				// subtract projection
				v.x -= 2 * vp * P.x;
				v.y -= 2 * vp * P.y;
				v.normalize (V);
				// move away from bounding circle
				P = new Point (X - ball.x, Y - ball.y);
				while (P.length > Math.sqrt ((R - r) * (R - r))) {
					ball.x += v.x;
					ball.y += v.y;
					P = new Point (X - ball.x, Y - ball.y);
				}
			}
		}
	}
}

Makc3d said I could choose one of his excellent wonderfl.net pieces and submit it to the contest. This snippet creates a ball that bounces off the inside of a circle. I thought this was a pretty unique way to go about doing this – and found it easy to add gravity and other cool features to it.

Have a look at the swf over at wonderfl….

Some Makc3d links:
>> http://makc3d.wordpress.com/
>>http://code.google.com/p/makc/
>> http://wonderfl.net/user/makc3d

Makc3d elaborated on his code a bit via e-mail. He said that his technique sacrifices accuracy for simplicity… and that if you simplify too much it would be easy to break the code. “e.g. comment out piece of code where it says “move away from bounding circle””…

Here is a picture that Makc3d drew explaining why you need to multiply by 2:

Read snippet: Bounce Ball Inside a Circle

Google Analytics Utility

package com.hapticdata.utils
{
	import flash.external.ExternalInterface;
	/**
	 * Simplifies posting to Google's Analytics Tracker, allows easily disabling for development phase
	 * and uses ExternalInterface rather than navigateToURL
	 * @class Urchin 
	 * @author Kyle Phillips - <a href="http://www.haptic-data.com">http://www.haptic-data.com</a>
	 * @created October 28, 2008
	 * @example Analytics.post("section");
	 */
	
	
	public class Analytics
	{
		
		public static var enabled:Boolean = true;
		//appended as a directory to all trackings
		public static var swfID:String="/flashevent/";
		//correct for default snippet. Change this if you have a custom-wrapped analytics method
		public static var functionToCall:String = "pageTracker._trackPageview";
		
		/**
		 * Will invoke the set javascript function
		 * @param location:String - a string identifying where the user is in the site
		 */
		public static function post(location:String):void
		{
			if(enabled && ExternalInterface.available)
			{
				ExternalInterface.call(functionToCall,swfID+location);
			}
		}
	}
}

This contest entry by Kyle Phillips is a utility class for dealing with google analytics. If you haven’t messed with google analytics I suggest you give it a try.

Kyle Phillips links:
>> http://workofkylephillips.com
>> http://labs.hapticdata.com

I usually find myself adding google analytics code in a very hacky way… usually because the client asks for it at the 11th hour. Using a class like Kyle’s would enable you to simply add the tracking code from the start and then if the client doesn’t ask for it… you can just keep the class disabled… or charge more when you offer google analytics tracking for “phase 2” of the project 😉

Read snippet: Google Analytics Utility

Paste Your Interface

Are you working on something right now that makes use of interfaces? Copy and paste an interface into the comments of this post (no need for code tags or anything)….

package app{
	
	import flash.events.IEventDispatcher;
	
	public interface IBaseModel extends IEventDispatcher{
		
		function set decimal(val:int):void;
	
		function get decimal():int ;
		
		function get stringValue():String; 
		
		function get errorMessage():String;
		
		function set base(val:int):void;
		
		function get base():int;
		
		function startCounting(interval:Number, changeBy:Number):void;
		 
		function stopCounting():void;
	}
}
Read snippet: Paste Your Interface

BitmapData Frame Animation (w/ linked list)

[SWF(width = 100, height = 100)]
var circle:Shape = new Shape();
with(circle.graphics) beginFill(0x000000), drawCircle(20,20,20);

var currFrame:Frame;

// populate the linked list
generateAnimation();

var canvas:BitmapData = new BitmapData(stage.stageWidth,stage.stageHeight,false, 0x000000);
addChild(new Bitmap(canvas));
var loc:Point = new Point(20, 20);

addEventListener(Event.ENTER_FRAME, onLoop);
function onLoop(evt:Event):void {
	// clear the canvas
	canvas.fillRect(canvas.rect, 0x000000);
	// draw the current frame
	canvas.copyPixels(currFrame.bitmap, currFrame.bitmap.rect, loc, null, null, true);
	// get the next frame of the animation
	currFrame = currFrame.next;
}

// generate and capture 40 bitmaps by altering the colorTransform of the circle shape
function generateAnimation():void{
	var channel:uint = 0;
	var ct:ColorTransform = new ColorTransform();
	var increase:Boolean = true;
	var firstFrame:Frame;
    var pFrame:Frame;
	for (var i:int = 0; i<40; i++){
		if (increase){
		   channel += 10;
		   if (channel == 200){
			  increase = false;   
		   }
		}else{
		   channel -= 10;
		}
		ct.color = channel << 16 | channel << 8 | channel;
		circle.transform.colorTransform = ct;
		// populate linked list
		currFrame = capture(circle); 
		if (pFrame){
		   pFrame.next = currFrame;
		}
		if (i == 0){
		   firstFrame = currFrame;
		}
		pFrame = currFrame;
	}
	// close the list
	currFrame.next = firstFrame;
	currFrame = firstFrame;
}

// create the Frame instance and draw the circle to it
// preserving the colorTransform information
function capture(target:Shape):Frame{
	var frame:Frame = new Frame();
	frame.bitmap = new BitmapData(target.width, target.height, true, 0x00000000);
	frame.bitmap.draw(target, null, target.transform.colorTransform);
	return frame;
}

Requires this little Frame class

package {
	import flash.display.*;
	final public class Frame{
		public var bitmap:BitmapData;
		public var next:Frame;
	}
}

This is a small test I did today to see how easy it would be to use a circular linked list to loop an animation of bitmaps. I did this because I was thinking about using some animated sprites in conjunction with Utils3D.projectVectors() to do an orthographic 3D demo with lots of animating sprites. In the past I’ve had up to 7,000 animated sprites running nicely using arrays and copyPixels… figured it would be interesting to try and do the same with a circular linked list.

When compiled, this test simply draws a circle that fades from black to gray and back again… Pretty boring, but I threw it up over at wonderfl anyway… check it out.

I recently saw a few tweets (forget who from) about using the final keyword on linked list nodes… haven’t tested it myself but it’s supposed to be faster…

Read snippet: BitmapData Frame Animation (w/ linked list)

Three Color Triangle

/*
*       Petri Leskinen, Finland
*       25 October 2009
*       pixelero.wordpress.com
*
*       Actionscript 3.0, Flash CS3, Flash Player 10
*
*       threeColorTriangle
*       draws a triangle with a gradient fill of three colors for each vertex
*       using graphics.drawTriangles and a BitmapData of size 2x2
*/
function threeColorTriangle(
      point0:Point, color0:uint,
      point1:Point, color1:uint,
      point2:Point, color2:uint):void {

      //      create a  bitmap of size 2x2 pixels
      var bmd:BitmapData = new BitmapData(2,2,true);
      //      copy colors to bitmap
      //      the fourth color is average of color1 and color2
      bmd.setVector(bmd.rect,
              Vector.<uint>([color0,color1,color2,
                                         (color1+color2)>>1
                                         ]));

      //      draw triangle
      this.graphics.beginBitmapFill(bmd,null,false,true /* =smooth */ );
      this.graphics.drawTriangles(
              // x,y -coordinates
              Vector.<Number>([
                      point0.x,point0.y,
                      point1.x,point1.y,
                      point2.x,point2.y]),
              // indices
              Vector.<int>([0,1,2]),
              // texture coordinates
              Vector.<Number>([0,0, 1,0, 0,1])
              );
}


// demo, let's draw some of these on the stage
randomize();
function randomize():void {
      this.graphics.clear();

      for (var i:int = 0;i<128;i++) {
              //      pick some random colors
              var color0:uint = 0xFFFFFFFF;
              var color1:uint = 0xFFFFFF*Math.random() | 0xFF000000;
              var color2:uint = 0xFFFFFF*Math.random() | 0xFF000000;

              //      random points 
var point0:Point = new Point(Math.random()*stage.stageWidth,
            Math.random()*stage.stageHeight);
var point1:Point = new Point(point0.x+200*(Math.random()-Math.random()),
            point0.y+200*(Math.random()-Math.random()));
var point2:Point = new Point(point0.x+200*(Math.random()-Math.random()),
            point0.y+200*(Math.random()-Math.random()));

        threeColorTriangle(point0, color0, point1, color1, point2,  color2);
      }
}

This snippet is by Petri Leskinen (pixelero). It draws a triangle with a gradient fill of three colors for each vertex using Graphics.drawTriangles and a BitmapData of size 2×2. This is the simplest case, it can easily be extended to four colors or maybe to use a larger 3×3, 4×4 etc… bitmap.

Here’s a still…

Read snippet: Three Color Triangle

Triangular Numbers

[SWF(width = 500, height = 500)]
 
var txt:TextField = TextField(addChild(new TextField()));
txt.defaultTextFormat = new TextFormat("_sans", 4);
txt.width = stage.stageWidth;
txt.height = stage.stageHeight+4;
txt.z = -1;
txt.x = stage.stageWidth
txt.rotation = 90;
var count:int = 0;
addEventListener(Event.ENTER_FRAME, onLoop);
function onLoop(evt:Event):void{
     count++;
	 txt.appendText(triangular(count).toString(2) + "n");
	 txt.scrollV= txt.maxScrollV;
}
function triangular(n:int):int{
       return (n * (n + 1)) / 2;
}

Calculate some triangular numbers… (n * (n + 1)) / 2….

Check out the swf on wonderfl

Read snippet: Triangular Numbers

Flowing Leaves (optical illusion)


Saw this optical illusion today… figured I’d make a snippet to create a few variations on the illusion…

[SWF( backgroundColor=0x2E7999, width=780, height = 600) ]

var leafNum:Number = 375;
var spacing:Number = 12;
var cols:Number = 25;
var hh:Number = stage.stageHeight / 2;
var hw:Number = stage.stageWidth / 2;

for (var i:Number = 0; i<leafNum; i++){
	var leaf:Shape = makeLeaf();
	leaf.scaleX = leaf.scaleY = 0.25;
	leaf.rotation = 90;
	leaf.x = 50 + (i % cols) * (leaf.width + spacing);
	leaf.y = 40 + int(i / cols) * (leaf.height + spacing);
	var dx:Number = leaf.x - hw;
	var dy:Number = leaf.y - hh;
	leaf.rotation = Math.sqrt(dx * dx + dy * dy);
}

function makeLeaf():Shape{
	var leaf:Shape = Shape(addChild(new Shape()));
	leaf.graphics.beginFill(0x9DC4D4);
	scaleYcircle(leaf.graphics, 50, .65, false);
	leaf.graphics.endFill();
	leaf.graphics.lineStyle(2, 0x003366, 1, false, "none", CapsStyle.SQUARE, JointStyle.MITER);
	scaleYcircle(leaf.graphics, 50, .65);
	leaf.graphics.lineStyle(2, 0xFFFFFF, 1, false, "none", CapsStyle.SQUARE, JointStyle.MITER);
	scaleYcircle(leaf.graphics, -50, .65);
	return leaf;
}
 

// original circle function by senocular (www.senocular.com) from here http://www.actionscript.org/forums/showthread.php3?s=&threadid=30328
// circle that can be scaled on the y axis
function scaleYcircle(g:Graphics, r:Number, s:Number = 1, isHalf:Boolean=true):void {
	 
	var c1:Number = r * (Math.SQRT2 - 1);
	var c2:Number = r * Math.SQRT2 / 2;
	var rs:Number = r * s, c1s:Number = c1 * s, c2s:Number = c2 * s;
	var x_r:Number =  -r, y_r:Number = -rs, x_c2:Number =  -c2;
	var y_c2:Number =  -c2s, x_c1:Number =  -c1, y_c1:Number =  -c1s
	g.moveTo(r, 0), g.curveTo(r, c1s, c2, c2s);
	g.curveTo(c1, rs, 0, rs), g.curveTo(x_c1,rs, x_c2, c2s);
	g.curveTo(x_r, c1s, x_r, 0);
	if (!isHalf){
	 g.curveTo(x_r,y_c1,x_c2,y_c2);
	 g.curveTo(x_c1,y_r,0,y_r), g.curveTo(c1,y_r,c2,y_c2);
	 g.curveTo(r,y_c1,r,0);
	}
}
Read snippet: Flowing Leaves (optical illusion)

ByteArray.readUTFBytes()

var m:ByteArray = new ByteArray();
var bytes:Array = [0x41, 0x63, 0x74, 0x69, 0x6F, 0x6E, 0x20, 
				   0x53, 0x6E, 0x69, 0x70, 0x70, 0x65, 0x74]
for (var i:int = 0; i < bytes.length; i++){
	m.writeByte(bytes[i]);
}

m.position = 0;
 
trace(m.readUTFBytes(bytes.length));

I was messing around with a hex editor today and decided to start playing with ByteArray for the first time in awhile. Just wrote this as a little warm up… Try running it to see what it traces out…

Read snippet: ByteArray.readUTFBytes()

Bitwise OR | and Variable Function Arguments (bitwise flags)

const A:uint = 1;
const B:uint = 2;
const C:uint = 4;
const D:uint = 8;
const E:uint = 16;

function orArgs(args:uint):void{
	if (args & A){
		trace("A");
	}
	if (args & B){
		trace("B");
	}
	if (args & C){
		trace("C");
	}
	if (args & D){
		trace("D");
	}
	if (args & E){
		trace("E");
	}
}

// test out the function: 
orArgs(A | B);
trace("--");
orArgs(A | C | E);
trace("--");
orArgs(B | E | D);
trace("--");
orArgs(C | A);

/* outputs: 
A
B
--
A
C
E
--
B
D
E
--
A
C
*/

If you’ve every used Array.sort(Array.NUMERIC | Array.DESCENDING) you should have at least a vague idea about what this snippet is doing. It shows how you can pass a variable number of arguments to a function using | (bitwise OR) and & (bitwise AND). I believe the correct term for these kind of arguments is “bitwise flags”. This snippet works by having a series of constant values… in this case A – E. Each constant is assigned an unsigned integer… now you may not see the significance of the values 1, 2, 4, 8 and 16 until you see them in binary… get ready this is a pretty cryptic description…

A = 00001 = 1
B = 00010 = 2
C = 00100 = 4
D = 01000 = 8
E = 10000 = 16

If we OR all these together we get: 11111… If we do:

A | E
00001 | 10000

we end up with 10001…

…we can then check which values are stored in the resulting unsigned integer by using AND:

check for A… 10001 & 00001 = 00001 = true
check for E… 10001 & 10000 = 10000 = true
check for C… 10001 & 00100 = 00000 = false

That’s it… I just guessed at the way this was being done… if you have another way to do the same thing, feel free to post it in the comments….

Read snippet: Bitwise OR | and Variable Function Arguments (bitwise flags)