Something I do a fair bit on this website is use functions as objects. Here is a simple example post on wonderfl. Timeline code and a brief description are available below.
Here is a still of what it generates and below you'll find the timeline as code:
Actionscript:
-
[SWF(width = 500, height=500)]
-
-
var canvas:BitmapData = new BitmapData(800,800,false, 0x000000);
-
addChild(new Bitmap(canvas,"auto",true));
-
scaleX = scaleY = 500 / 800
-
-
-
var walkerNum:int = 50;
-
var walkers:Vector.<Function> = new Vector.<Function>(walkerNum, true);
-
-
makeWalkers();
-
runWalkers();
-
-
function makeWalkers():void{
-
for (var i:int = 0; i<walkerNum; i++){
-
walkers[i] = makeWalker();
-
}
-
}
-
function runWalkers():void{
-
addEventListener(Event.ENTER_FRAME, onRun);
-
}
-
function onRun(evt:Event):void{
-
for (var i:int = 0; i<walkerNum; i++){
-
walkers[i]();
-
}
-
}
-
-
function makeWalker(xp:Number=400, yp:Number=400):Function{
-
var x:Number = xp, y:Number = yp;
-
var rad:Number = Math.random() * 4;
-
var theta:Number = Math.random() * Math.PI * 2;
-
var speed:Number = 0.01 * Math.random() * 2
-
if (int(Math.random() * 2) == 1){
-
speed *= -1;
-
}
-
return function():void{
-
x += rad * Math.cos(theta);
-
y += rad * Math.sin(theta);
-
theta += speed
-
if (int(Math.random() * 100) == 1){
-
theta = Math.random() * Math.PI * 2;
-
}
-
if (x> 800 || x <0 || y> 800 || y <0){
-
x = xp, y = yp;
-
}
-
canvas.setPixel(x, y, 0xFFFFFF);
-
}
-
}
The basic trick is to have a function return a function. The original function initializes typed local variables and the returned function has access to these values. This is one of many ways to do OOP style coding using functions alone. This is really only for fun and for speed coding reasons - it's worth noting that this method is is significantly slower than using actual classes. I still have lots of fun with it despite the downsides.
7 Comments
This is soooo slick! I always use an Object Class that contains a property and then force that into an Array and loop though those. This cuts out that unnecessary step. Thanks for the insightt!
I think I saw Higgs boson somewhere there.
@makc3d ha yeah i thought it looked like an image from CERN a little bit
Nice, but I guess it would be better to have canvas as a parameter of the anonymous function created by makeWalker.
not a bad idea at all… you can fork it on wonderfl if you like.
I love this man. There are some pretty nice things this effect could be used for and the code is sweet. great idea!
thanks phil