particle system
星期四, 12月 25th, 2008
Particle.as
{
import flash.display.*;
public class Particle
{
public var clip : DisplayObject;
public var xVel : Number = 0;
public var yVel : Number = 0;
public var drag : Number = 1;
public var gravity : Number = 0;
public var shrink : Number = 1;
public var fade : Number = 0;
// This is the constructor, a special function used
// to create this particle object.
public function Particle(symbolclass : Class, target : DisplayObjectContainer,
xpos : Number, ypos : Number)
{
// make the particle clip
clip = new symbolclass();
// add it to the target (usually the stage)
target.addChild(clip);
// and move it to its starting position
clip.x = xpos;
clip.y = ypos;
}
public function update() : void
{
// add the velocity to the clip's position
clip.x += xVel;
clip.y += yVel;
// apply drag
xVel *= drag;
yVel *= drag;
yVel += gravity;
clip.scaleX *= shrink;
clip.scaleY *= shrink;
clip.alpha -=fade;
}
// take the clip off the stage
public function destroy():void
{
clip.parent.removeChild(clip);
}
}
}
Particle.fla
var particles:Array = new Array();
// call frameLoop every frame
addEventListener(Event.ENTER_FRAME, frameLoop);
var _isgravity:Number=-1;
function frameLoop(e:Event) {
var particle:Particle;
// loop through the array of particles and update each one
for (var i : int = 0; i < particles.length; i++) {
// update the particle at index i
particles[i].update();
}
// make a new particle
particle = new Particle(Spark, this, 200, 100);
// set our particle's velocity
particle.xVel = randRange(-1,1);
particle.yVel = 0;
// add drag
particle.drag = 0.97;
// add gravity
particle.gravity = _isgravity;
// randomise initial particle size
particle.clip.scaleX = particle.clip.scaleY = randRange(0.5, 0.8);
// add shrink
particle.shrink = 1.02;
// add fade
particle.fade = 0.01;
// set the particle's starting alpha
particle.clip.alpha = 0.6;
// and add it to the array of particles
particles.push(particle);
// if there are more than 80 particles delete the first
// one in the array...
while (particles.length>60) {
particle = particles.shift();
particle.destroy();
}
}
// returns a random value between min and max
function randRange(min:Number, max:Number) {
return Math.random() * max - min + min;
}
gplus.addEventListener(MouseEvent.CLICK, f_gplus);
gminus.addEventListener(MouseEvent.CLICK, f_gminus);
function f_gplus(e:MouseEvent):void {
_isgravity+=.1;
}
function f_gminus(e:MouseEvent):void {
_isgravity-=.1;
}


