Simple Particles

Actionscript:
  1. stage.frameRate = 30;
  2. addEventListener(Event.ENTER_FRAME, onLoop);
  3. function onLoop(evt:Event):void{
  4.     if (int(Math.random()*5)==1){
  5.       for (var i:int= 0; i<10; i++) createParticle();
  6.     }
  7. }
  8.  
  9. function createParticle():void{
  10.     var s:MovieClip = new MovieClip();
  11.     s.graphics.beginFill(0);
  12.     s.graphics.drawCircle(0,0,Math.random()*10 + 2);
  13.     s.velX = Math.random()*10-5
  14.     s.velY =  Math.random()*10-5
  15.     s.posX = s.x = 200;
  16.     s.posY = s.y = 200;
  17.     addChild(s);
  18.     s.addEventListener(Event.ENTER_FRAME, onRunParticle);
  19. }
  20.  
  21. function onRunParticle(evt:Event):void {
  22.     var s:MovieClip = MovieClip(evt.currentTarget);
  23.     s.posX += s.velX;
  24.     s.posY += s.velY;
  25.     s.scaleX = s.scaleY -=  .04;
  26.     if (s.scaleX <0){
  27.         removeChild(s);
  28.         s.removeEventListener(Event.ENTER_FRAME, onRunParticle);
  29.     }
  30.     s.x = s.posX;
  31.     s.y = s.posY;
  32. }

Nothing special here. But my students are always asking me about this - in class I have them alter this code to make fire, water and abstract particle systems.

This entry was posted in motion, random and tagged , , , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

6 Comments

  1. Posted November 26, 2008 at 10:15 am | Permalink

    just an FYI you pasted the onRunParticle method twice in the above code.

  2. Posted November 26, 2008 at 10:36 am | Permalink

    cool thanks… fixed.

  3. anand kumar dwivedi
    Posted July 14, 2009 at 2:13 am | Permalink

    yr book is good

  4. Posted July 14, 2009 at 6:47 am | Permalink

    thanks anand

  5. Lisa
    Posted September 9, 2009 at 12:13 pm | Permalink

    I love your book. Am a beginner and am working my way through. Regarding the above … neat. I’m playing around with it and wondering, if I were going to set these to be in different (random) colors, how would I do that? I’m thinking something along the lines of:

    s.alpha = Math.random()

    but that’s about all I can think of LOL, and would it go right after the drawCircle line (line 12) or or right before addChild (line 17)? Just curious. thanks.

  6. Posted September 9, 2009 at 12:25 pm | Permalink

    just change line 11:

    s.graphics.beginFill(0);

    to:

    s.graphics.beginFill(Math.random() * 0xFFFFFF);

    and be sure to look at the motion chapter from the book - at the end of the chpater we do exactly this with random colors.

    Glad you are enjoying the book :)

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*