Simple Starfield

This is a very basic starfield attempt. It was for me just a kind of HelloWorld programm for testing the new Flex3 SDK using ActionScript and the basic Bitmapdata concept.

Action

Technique

Platform: Flash using Flex3.0 SDK and pure Actionscript3.0.

Source

Stars.as
package  
{
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.Sprite;
	import flash.events.Event;
	
	/**
	* ...
	* @author benny!weltenkonstrukteur.de
	*/	
	public class Stars extends Sprite
	{
		
		private var bitmap:Bitmap;
		private var canvas:BitmapData;
		private var sw:int, sh:int, snum:int;
		private var stars:Array;
		private var colors:Array;
		
		public function Stars() {
			snum = 250;
			sw = stage.stageWidth;
			sh = stage.stageHeight;
			colors = new Array(
						"0x000000",		// never used
						"0xFFFFFF",
						"0xBBBBBB",
						"0x888888",
						"0x444444"
					);
			
			init();
			
			addEventListener( "enterFrame", run );
		}
		
		private function init():void {
			canvas = new BitmapData( sw, sh, false );
			bitmap = new Bitmap( canvas );
			stars = new Array( snum );
			for ( var i:int = 0; i < snum ; i++ ) {
				stars[i] = new StarModel();
			}
			addChild( bitmap );
		}
		
		private function run( e:Event ):void {
			canvas.lock();
			
			canvas.fillRect( canvas.rect, 0x111122 );
			for ( var i:int = 0; i < snum ; i++ ) {
				stars[i].move();
				canvas.setPixel( stars[i].sx, stars[i].sy, colors[ stars[i].scol ] );
			}
			
			canvas.unlock();			
		}
		
		
	}
	
}

StarModel.as
package  
{
	
	/**
	* ...
	* @author benny!weltenkonstrukteur.de
	*/
	public class StarModel 
	{
		
		private var x:Number, y:Number, z:Number, zv:Number;
		public var sx:int, sy:int, scol:int;
		
		public function StarModel() {
			init();
		}
		
		public function move():void {
			z = z - zv;
			sx = (int)(x / z * 100 + 320 );
			sy = (int)(y / z * 100 + 200 );
			scol = Math.round( z / 100 );
			if ( sx < 0 || sx > 640
				|| sy < 0 || sy > 400
				|| z < 1 ) {
					init();
				} 			
		}
		
		private function init():void {			
			this.x = Math.random() * 1000 - 500
			this.y = Math.random() * 1000 - 500 ;
			this.z = Math.random() * 500 + 100;
			this.zv = Math.random() * 5 + 1;
			this.scol = Math.round(this.z / 100);
		}
	}
	
}