PixelMotion
/**
* Copyright JorgeBraccini ( http://wonderfl.net/user/JorgeBraccini )
* MIT License ( http://www.opensource.org/licenses/mit-license.php )
* Downloaded from: http://wonderfl.net/c/kU55
*/
package {
import flash.events.TimerEvent;
import flash.utils.Timer;
import flash.display.BitmapData;
import flash.display.Bitmap;
import flash.geom.Point;
import flash.display.Sprite;
public class PixelMotion extends Sprite {
private var WIDTH:Number;
private var HEIGHT:Number;
private var _pixelStage:Bitmap;
private var _pixelCollection:Array;
private var _renderClock:Timer;
public function PixelMotion() {
init();
}
private function init():void {
//inittrace(this);
WIDTH = stage.stageWidth;
HEIGHT = stage.stageHeight;
_renderClock = new Timer(33);
_renderClock.addEventListener(TimerEvent.TIMER, handleRenderTick);
buildStage();
buildPixels(10000);
_renderClock.start();
}
private function buildPixels(q:Number):void {
var pixel:Pixel;
_pixelCollection = [];
for (var i:Number = 0; i < q; i++){
pixel = new Pixel(WIDTH, HEIGHT);
_pixelCollection.push(pixel);
}
}
private function render():void {
var bd:BitmapData = new BitmapData(WIDTH, HEIGHT, false, 0xffffff);
for each(var pixel:Pixel in _pixelCollection){
pixel.update();
bd.setPixel(pixel.pos.x, pixel.pos.y, 0x000000);
}
_pixelStage.bitmapData = bd;
}
private function buildStage():void {
_pixelStage = new Bitmap();
addChild(_pixelStage);
}
private function handleRenderTick(e:TimerEvent):void { render(); }
}
}
import flash.geom.Point;
class Pixel {
private var _pos:Point;
private var _maxWidth:Number;
private var _maxHeight:Number;
private var _dx:Number = 0;
private var _dy:Number = 0;
public function Pixel(maxWidthPos:Number, maxHeightPos:Number){
_maxWidth = maxWidthPos;
_maxHeight = maxHeightPos;
init();
}
private function init():void {
_pos = new Point(randRange(0, _maxWidth), randRange(0, _maxHeight));
while(_dx == 0) _dx = randRange(-2, 2);
while(_dy == 0) _dy = randRange(-2, 2);
}
public function update():void {
_pos.x += _dx;
_pos.y += _dy;
if(_pos.x > _maxWidth || _pos.x < 0) _dx*=-1;
if(_pos.y > _maxHeight || _pos.y < 0) _dy*=-1;
}
public function get pos():Point { return _pos; }
}
import flash.display.Sprite;
import com.bit101.components.TextArea;
var textarea:TextArea;
function inittrace(mainRef:Sprite):void {
textarea = new TextArea();
textarea.editable = false;
textarea.width = mainRef.stage.stageWidth;
textarea.height = mainRef.stage.stageHeight / 3;
textarea.y = mainRef.stage.stageHeight - textarea.height;
mainRef.addChild(textarea);
}
function doTrace(...args):void {
var s:String = "";
for each(var field:* in args) s += field.toString()+" ";
s+="\n";
try {textarea.text = s + textarea.text;}catch (e:Error){}
}
function randRange(minNum:Number, maxNum:Number):Number {
return (Math.floor(Math.random() * (maxNum - minNum + 1)) + minNum);
}
var trace:Function = doTrace;