This is a simple starfield with two MovieClip methods. randomSpace gives a movieclip a random xyz position in space. These would be the actual 3D coordinates of the stars in the real world. The placeInSpace method calculates the actual screen coordinates of the movieclip and also sets the positions in _x and _y. This method also scales the size of the movieclip by setting _xscale and _yscale so nearer stars appear bigger.
Download Source File: Flash5_Starfield.zip
Code:
MovieClip.prototype.placeInSpace = function(id) { var ratio = this.focaldistance / Math.sqrt(this[id].z * this[id].z); this[id]._x = this[id].x * ratio; this[id]._y = this[id].y * ratio; this[id]._xscale = this[id]._yscale = 1000 / this[id].z; } MovieClip.prototype.randomPlace = function(id) { var radius = this.rmin + (this.rmax - this.rmin) * Math.random(); var polar = 2 * Math.PI * Math.random(); this[id].x = radius * Math.cos(polar); this[id].y = radius * Math.sin(polar); this[id].z = this.zmin + (this.zmax - this.zmin) * Math.random(); }
With these two methods in hand we can create a parent host clip that will call these methods on every child movieclip. On startup the code block executes inside the onClipEvent (load) handler. It populates the stage with the dot library item. You could also use bitmaps as sprites. Finally as the onClipEvent (enterFrame) handler exectues on every frame, it calls the placeInSpace method to present them on the screen. When a movieclip has passed the limit of onscreen display we recycle it with the randomPlace method.
Code:
onClipEvent (load) { this.count = 50; this.speed = 5; this.focaldistance = 25; this.rmin = 50; this.rmax = 1000; this.zmin = 10; this.zmax = 300; for(var i = 0; i < this.count; i++) this.attachMovie('dot', i, i); } onClipEvent (enterFrame) { for(var i = 0; i < this.count; i++) { if((this[i].z -= this.speed) <= 0) this.randomPlace(i); this.placeInSpace(i); } }