为了实现粒子在视觉上消失的效果,通过设置Particle的fade属性为0~1之间的小数,使它的alpha逐渐降低,从而达到淡出粒子的目的。
package{ import flash.display.Sprite; import flash.events.Event; [SWF(width="800",height="600",backgroundColor="0xffffff",frameRate="31")] public class ParticleFade extends Sprite{ private var numbers:Number = 20; private var particles:Array; public function ParticleFade(){ particles=new Array(); stage.addEventListener(Event.ENTER_FRAME, onEnterFrame); } private function onEnterFrame(e:Event):void{ if(particles.length < numbers){ var ball:Ball=new Ball(12, 0x00ff00, 1, 0x000000, 1); addChild(ball); ball.xVelocity=Math.random() * 20 - 10; ball.yVelocity=Math.random() * 20 - 10; ball.gravity=0.9; ball.growX = 1.05; ball.growY = 1.05; ball.fade = 0.98; ball.x=stage.stageWidth/2; ball.y=stage.stageHeight/4; particles.push(ball); } for (var i:int=0; i < particles.length; i++){ var particle:Ball=particles[i]; particle.update(); if (particle.x - particle.radius > stage.stageWidth || particle.x + particle.radius < 0 || particle.y - particle.radius > stage.stageHeight || particle.y + particle.radius < 0){ particle.xVelocity=Math.random() * 20 - 10; particle.yVelocity=Math.random() * 20 - 10; particle.x=stage.stageWidth / 2; particle.y=stage.stageHeight / 4; particle.scaleX = particle.scaleY = 1; particle.alpha = 1; } } } } }
在初始化粒子的循环中将粒子的fade属性设置为0.98,在遍历粒子数组并使其运动的循环中调用update函数使粒子运动并改变它的alpha属性。超过环境边界后,再重置它的速度和位置,并将它的alpha设置回1,从而在下一次的遍历循环中演示它的fade属性。