Wednesday, July 4, 2012

AS3: Mesmerizing Stars

Someone has asked me how to create a 'mesmerizing galaxy' in Flash. Well, there's definitely more than one way of doing it and one of them will be tweening the whole animation... which is kind of crazy. Well here's an easier way of doing it. :P

Main.as (The .as file of the fla file)
package com.massStar
{
 import flash.display.MovieClip;
 import flash.events.Event;
 
 public class Main extends MovieClip 
 {
  public function Main() 
  {
   //Upon adding the flash file to the stage
   this.addEventListener(Event.ADDED_TO_STAGE, stageEvent);
  }
  
  //Create a grid of animated stars
  private function stageEvent(event:Event):void
  {
   var tempStar:Star_mc;
   for(var i:int = 0; i <= 400; i += 40)
   {
    for(var j:int = 0; j <= 320; j += 40)
    {
     tempStar = new Star_mc();
     tempStar.x = i;
     tempStar.y = j;
     this.addChild(tempStar);
    }
   }
  }
 } 
}
Star.as (The .as file of the star animation)
package com.massStar
{
 import flash.display.MovieClip;
 import flash.events.Event;
 
 public class Star extends MovieClip 
 {
  public function Star() {
   //Upon adding the animated star on stage...
   this.addEventListener(Event.ADDED_TO_STAGE, stageEvent);
  }
  
  private function stageEvent(event:Event)
  {
   //we will select a random frame and start playing the
   //animation sequence from that random frame
   var tempFrame:int = this.totalFrames;
   this.gotoAndPlay(Math.floor(Math.random() * tempFrame));
  }
 }
}
* Click here for the demo.
^ Click here for the source files of the demo.

No comments:

Post a Comment