Tuesday, November 10, 2009

Snow effect with actionscript 3

Recently, I need some snow effect with actionscript. I search the net for samples, and found one. http://www.tutorio.com/tutorial/flash-snow It was written on ActionScript 2 but the idea was simple.
  • Create several copies of snow Sprite
  • Let the y-velocity of these snow sprites random
  • Let the x-positions of these sprites swing by using sine (or cosine) function. 
With the randomization, the output looks realistic. (It was a 10 minute coding, sorry for the quality).




Just create a movie clip with linkage class name Snow in Flash Proffesional. Put any graphics you want in it (just a small white circle will be fine). Create anothor movie clip on the stage with linkage class name Snowing. Just play with the randomization parameters for different effects.

package 
{
 import flash.display.Sprite;
 import flash.events.Event;

 public class Snow extends Sprite
 {
  private var yVelocity:Number;
  private var xRadius:Number;
  private var xIncrement:Number;
  private var xAngle:Number;
  private var xOrig:Number;
  public function Snow()
  {
   yVelocity = 2 + Math.random() * 5;
   xRadius = 10 + Math.random() * 100;
   xIncrement = 0.001 + Math.random() * 0.05;
   xOrig = Math.random() * 1000;
   xAngle = 2*Math.random()*Math.PI;
   x = xOrig;
   y = Math.random() * 600;
   alpha = 0.2+0.8*Math.random();
   scaleX = scaleY = 0.2+0.8*Math.random();
   addEventListener(Event.ENTER_FRAME, onEnterFrame);
  }
  private function onEnterFrame(e:Event)
  {
   this.y += yVelocity;
   this.x = xOrig + xRadius*Math.sin(xAngle);
   xAngle += xIncrement;
   if (this.y >= 600)
    this.y = 0;
  }
 }
 
}

package 
{
 import flash.display.Sprite;
 
 public class Snowing extends Sprite
 {
  private var numSnow:int = 1000;
  public function Snowing() 
  {
   for (var i = 0; i < numSnow; i++)
   {
    var snow:Snow = new Snow();
    addChild(snow);
   }
  }
  
 }
 
}

Happy snowing...

No comments: