Create a Rain Effect in Flash Using ActionScript 3.0

May 13th in Effects by Carlos Yanez

In this tutorial we'll create a dynamic rain effect using ActionScript 3.0. The effect can be customized in many ways by just changing a few lines of code. Let's get started!

PG

Author: Carlos Yanez

Carlos is a Web/Logo Designer, Flash Developer with passion for great designs and cool applications.

Final Result Preview

Let's take a look at the final effect we'll be working towards:

Step 1 - Brief Overview

We'll draw a simple rain drop, then using our ActionScript skills we'll duplicate, move and position the MovieClip to get a nice rainy effect.

Step 2 - The .fla Document

Create a new ActionScript 3 document (File > New...). Set the Stage size to your desired dimensions, I've used 600 x 300 px.

Step 3 - Choose an Image

Add or draw an image to use as the background, I used a modified image by JinThai, licensed under Creative Commons.

Step 4 - Layers

Rename the first layer to "Background" then create another one and name it "Code" (we'll use this one to place our ActionScript on). You can lock the "Code" layer to avoid placement of unwanted drawings in there.

Step 5 - Creating the Drop

Create a graphic to use as the rain drop. Set its color to white and use a linear gradient for the alpha, mine is 40 to 15. Convert it to a MovieClip and name it "Drop", remember to check the "Export for ActionScript" checkbox.

Step 6 - Importing Required Classes

Let's start off some code in a separate ActionScript file:

package Classes
{
/* Import required classes */

import flash.display.MovieClip;
import flash.events.Event;

Here we import the Classes that we'll use. Remember that the word next to "package" is the name of the folder where our Class is located.

Step 7 - Extending the Class

//We need to extend the class so we can use the addChild() method. 
public class Rain extends MovieClip
{

Extending the MovieClip class will allow our class to inherit all of the methods, properties and functions that the MovieClip has. In this case we use it to get access to the addChild() method.

Step 8 - The Variables

Here we'll use an exclusive Flash Player 10 Class "Vector". Put simply, the Vector Class works like an Array, but is considerably faster.

private var offset:int = 50; //This is the offset area in pixels that the effect will take. Without this, the corners of the effect area will be rain-free
private var dropsNumber:int; //The number of rain drops; its value is set in the parameters
private var dropsVector:Vector.<MovieClip> = new Vector.<MovieClip>(); //The Vector that will store each rain drop

Step 9 - Main Function

public function init(drops:int, fallSpeed:int, windSpeed:int, hArea:int, vArea:int, dir:String):void
{

  dropsNumber = drops;

The main function, with some parameters making the effect easy to adapt to your needs. You can change the number of drops, the speed at which the drops fall, the speed at which the drops will move horizontally, the size of the effect area and the direction of the rain (left or right).

We set the dropsNumber value here.

Step 10 - Left or Right?

By default, the offset var is set to work with the left side, so we need to check where the rain will go and change the offset if the direction is right.

if (dir == "right")
{
offset *= -1;
}

Step 11 - Using the Drop MovieClip

In order to show various instances of the Drop MovieClip we have to create a new Drop Object inside a "For" statement:

for (var i:int = 0; i < drops; i++)

{

var drop:Drop = new Drop();

drop.fallSpeed=fallSpeed;
drop.windSpeed=windSpeed;
drop.dir=dir;
drop.hArea=hArea;
drop.vArea=vArea;

We use the "drops" variable to get the user defined number of drops and set the variables inside the MovieClip for later use.

Step 12 - Position

Set an initial random position for the Drops.

drop.x = Math.random() * (hArea + offset);

drop.y=Math.random()*vArea;

Step 13 - Scale

drop.scaleX = Math.round(((Math.random() * 0.8) + 0.3) * 10) / 10;
drop.scaleY=drop.scaleX;

This sets the scale of the Drops between 0.3 and the original size.

Step 14 - Adding the Drops to the Stage

dropsVector.push(drop);

addChild(drop);

} //End of For

inTheDirection();  

} //End of init function

This code adds the Drop MovieClip to the Vector and then to the stage. It also calls the "direction" function.

Step 15 - Direction

private function inTheDirection():void
{
for (var i:int = 0; i < dropsNumber; i++)
{
switch (dropsVector[i].dir)
{
case "left" :

   dropsVector[i].addEventListener(Event.ENTER_FRAME, moveLeft);

   break;

   case "right" :

   dropsVector[i].scaleX*=-1; //Our Drop was created going to the left, so we flip it to make it look like it's going to the right
   dropsVector[i].addEventListener(Event.ENTER_FRAME, moveRight);

   break;

   default :

   trace("Error");
    }
    }
    }

In this function we use another "For" to get access to the MovieClips inside the Vector. Then we check the direction parameter and add a Listener to the corresponding function. This will all take care of the movement and the position.

Step 16 - Move Functions

private function moveLeft(e:Event):void
{
e.target.x-=e.target.windSpeed;
e.target.y+=Math.random()*e.target.fallSpeed;

   if (e.target.y>e.target.vArea+e.target.height)
    {
    e.target.x = Math.random() * (e.target.hArea + (offset * 2));
    e.target.y=- e.target.height;
    }
    }

   private function moveRight(e:Event):void
    {
    e.target.x+=e.target.windSpeed;
    e.target.y+=Math.random()*e.target.fallSpeed;

   if (e.target.y>e.target.vArea+e.target.height)
    {
    e.target.x = Math.random() * (e.target.hArea - offset * 2) + offset * 2;
    e.target.y=- e.target.height;
    }
    }
    }
    }

This moves the Drops based on the parameters of the main function. It then resets the position when drops move outside the effect area.

Step 17 - Using the Class

That's the class finished, to make use of it we go back to the Flash IDE, open the Actions Panel and write:

import Classes.Rain;

var rain:Rain = new Rain();

rain.init(200, 50, 5, 600, 300, "left");

addChild(rain);

This will create a new Rain Object, then call the main function to start the effect. Finally we add the effect to the stage.

Conclusion

Remember that you can play with the parameters to get various effects and that you can also change the drops by drawing whatever you like. Keep trying different combinations to get the exact effect that you want.

I hope you enjoyed reading the tut as much as I did writing it. Thanks for reading!


Enjoy this Post?

We'd love your vote!

User Comments

( ADD YOURS )
  1. PG

    axel May 13th

    ummm maybe its just me but i cant see the rain

    ( Reply )
    1. PG

      Ian Yates May 13th

      Are you using Flash Player 10? That may be a good place to start..

      ( Reply )
  2. PG

    lawrence77 May 13th

    not so realistic…. :(

    But ok….

    ( Reply )
  3. PG

    MSFX May 13th

    some splashes would be nice, hard but nice ;)

    ( Reply )
    1. PG

      nilam September 25th

      nice

      ( Reply )
  4. PG

    Sean May 13th

    Excellent. Well Done.

    Am trying it out now whilst looking at it raining outside

    ( Reply )
    1. PG

      hey May 20th

      hey cool effect!!!!!!!!!! =)

      ( Reply )
  5. PG

    jack May 13th

    tnx :) nice tutorial!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!:)

    ( Reply )
  6. PG

    TPN May 13th

    I didn’t know it was this easy. Good job. :)

    ( Reply )
  7. Cool very well done! Anyone could suggest a good book to learn action script as a beginner?

    ( Reply )
    1. PG

      Alex May 13th

      Essential Actionscript 3 by Colin Moock would be a good place to start. It covers pretty much everything you’d need to know. I believe it’s published by O’Reilly.

      If you want to get into advanced scripted animation, you should check out any of the animation books by Keith Peters. I think the name of the book is Foundation Actionscript 3.0 Animation (theres a 2.0 as well), and it’s published by Friends of Ed I think. This is a very good book…I’ve read both the AS2 and 3 versions. Covers the basics right up to some crazy physics, scripted 3d (no papervision or builtin 3d…all by math), kinematics and all that good stuff.

      ( Reply )
      1. PG

        Ihack.ASIA May 13th

        Essential Actionscript 3 by Colin Moock will be better book for beginner.

    2. PG

      vibel November 1st

      For a beginner i suggest Learning Action 3.0 by Riche Shupe and Rosser.

      ( Reply )
  8. PG

    André May 13th

    Wow, there are some ways much easier to do this, sorry but it´s not so nice, and you can extend the Sprite instead of Movieclip, since this doesnt have a timeline animation.

    Another thing… but this is for everyone, the classes have a model, its not required, but it´s better, starting to the package… all the words are in lowercase, just the Class file in UpperCaseCamel, classes are in UpperCaseCamel, functions and variables in lowerCaseCamel, constants in UPPER_CASE. But its not required, just for better understanding for all, it is a model used everywhere in any language so the programers can understand better the code from others and know wich property is.

    I´ve created a tut and sent to moderator, but i think that there are a lot of others in front of me, i explained well how to work better with AS3.

    Next tut i will write a tut on how to work with AS3 and pixel bender filters, and also teach a little bit of pixel bender software.

    ( Reply )
    1. PG

      Alex May 13th

      Couldn’t agree more André. I think flashtuts+ should really have a coding conventions guide for all the tuts to follow. It would make life much easier on the people learning what to do, and it would be a first level check to make sure any code posted on the site is at a high enough standard.

      I don’t think flashtuts+ has anyone checking quality of the code for the tuts right now. It’s a typical problem with Flash tutorial websites. They just teach people how to get it done, not get it done right.

      ( Reply )
      1. PG

        Ian Yates May 13th

        That’s not a bad idea Alex (and André) – if anyone’s interested in putting together an ActionScript Conventions Guide, let me know! It would be a useful addition to the Flashtuts+ Author’s Brief and Templates used by contributors. Don’t forget, we’re barely two months old, but we’re certainly looking to improve content quality with every passing day.. Thanks :-)

      2. PG

        André May 13th

        I like the idea about doing a convention guide, and if approved i can help, because i see here some actionscript 3.0 tuts coded in timeline, or big codes that coud be done with much less code (this tut for example).

        One thing i´ve read at adobe´s website, actionscript 3.0 is projected to be coded in document classe and classes files, not in timeline, i think that timeline is still alive because of some people comming from AS 2.0 are still coding in timeline, and not accustomed with classes and document class, some of them are using the actionscript for years.

      3. PG

        Alex May 13th

        I’d be willing to help out with the convention guide as well. André and I could work on it together. I’d also be interested in seeing what Jesse Freeman has to say about it.

        I’d think that input from a few developers would lead to a better, more rounded guide. The last thing we need is a guide based wholly on someone’s personal preferences, rather than what’s common and best for the community.

      4. PG

        André May 13th

        I agree in help creating the guide convention for tutsplus, and teach the correct use of actionscript 3.0, explain about packages, importing classes, creating classes, extending classes, constructor functions and what it does, and most important, how to use them…

  9. PG

    Dario Gutierrez May 13th

    Nice effect and great tut Carlos.

    ( Reply )
  10. PG

    Franky May 13th

    Pretty cool. This generating loop would be awesome for gaming!

    ( Reply )
  11. PG

    Christo May 13th

    All code considerations aside, I can recommend an improvement using basically the same code:

    Make an additional layer, underneath the rain that is the same except that you reduce the size of the drops generated by perhaps 40% and use either blur (cpu intensive) or transparency on them and finally slow their descent down a bit relative to the drops in the foreground. These steps would simulate depth and distance. You might also randomly generate drops at a different size within a set of params for foreground drops and background drops to really get that depth effect. Just some ideas!

    ( Reply )
    1. PG

      André May 14th

      Wow, it coube be done adding more drops at time, and using random values for the speed, and relative to the speed value you can use alpha, scaleX and scaleY to simulate the depth. Maybe the using of a Tween engine can help a little bit in a gravity simulation…

      Just a suggestion =)

      ( Reply )
  12. PG

    Diego SA May 13th

    Perfect. But I’d set the drops to make a little changing of angle when it falls. You see, every drop has the same angle of fall. If you make a random looping of angle, make it becomes more realistic, what do you think?

    ( Reply )
  13. PG

    Mike May 13th

    Great tut and nice effect!, i don’t think the code is hard or long considering that you can customize the effect in many ways and that you can keep the class and use it in any project. Also i find the code very readable comparing to other tuts i’ve seen.

    ( Reply )
  14. PG

    Erick May 13th

    you remind me of my fraternity brother

    ( Reply )
  15. PG

    CgBaran Tuts May 14th

    Great effect nice tutorial thanks

    ( Reply )
  16. PG

    satish borkar May 19th

    Hi Carlos

    it’s really good

    keep it up………

    cheers
    satyaspb

    ( Reply )
  17. PG

    hey May 20th

    good effect!!!!!!!!!!!!!=)

    ( Reply )
  18. PG

    sandip kumar May 21st

    i’m folw this instraction but not sho in output of rain effect.
    There are not import ActionScript file. why

    ( Reply )
  19. PG

    sandip kumar May 21st

    nice

    ( Reply )
  20. PG

    Jason May 26th

    Great stuff, but can’t seem to open the .fla file to play around with. keep getting the “unexpected file format”. you make this using a mac? what version of flash was it made in.

    ( Reply )
  21. PG

    May29 May 28th

    These tutorials are great and all but could someone please explain where to put the the package, what to call the package so it will work, and how you refer to it from within your code?

    ( Reply )
  22. PG

    Saqib Butt May 30th

    hmmm great!!!

    ( Reply )
  23. PG

    anonymous May 31st

    I can’t seem to see the raindrops. and yes, i installed flash player 10

    ( Reply )
  24. PG

    aaaaa June 1st

    expecting identifier before lessthan?? help

    ( Reply )
  25. PG

    Sil3ntParadi9m June 4th

    I think maybe i shouldn’t have jumped in at the deep end for a newb. I got so lost in the codes that i came out with half a dozen errors! I think it’s just me, but this is what i got:
    1037: Packages cannot be nested.
    1084: Syntax error: expecting rightparen before semicolon.
    1013: The private attribute may be used only on class property definitions.
    1084: Syntax error: expecting semicolon before rightparen.

    These errors applied to 8 different lines of code, and as far as i can tell, they’re carbon copies of what’s written by Carlos.

    Any clues? Or should i just go back to class 101?

    ( Reply )
    1. PG

      d Joyce September 25th

      I copied the code exactly as it was inteh sample and i get this error…
      1084 syntax error: expecting identifier before less than

      ( Reply )
  26. PG

    Kieran June 11th

    What would the best way be to go about having this effect play up to a certain frame and then stop while the rest of the flash movie plays on? I’ve tried stop() on the keyframe where I want the rain to end but then the rain stops working completely.

    Any thoughts?

    ( Reply )
  27. PG

    katro June 25th

    I DID ITT!!!! YEEII!!

    ( Reply )
  28. PG

    ahmad June 26th

    Hmm…it’s great, cool animation

    thank for your tutorial

    I love it…^^

    ( Reply )
  29. PG

    uday July 15th

    hey great creativity. very nice

    ( Reply )
  30. PG

    james anderson August 8th

    hai this is very cool effct of the rain he also creating as very tuff its k very nice

    ( Reply )
  31. PG

    goldfinger August 22nd

    nice effect but i could’nt do it

    ( Reply )
  32. PG

    kruti August 26th

    not working….

    ( Reply )
  33. PG

    d Joyce September 25th

    I get this error…i copied this straight from the example
    1084 syntax error: expecting identifier before less than

    ( Reply )
  34. PG

    Chris October 13th

    Hello Carlos
    I gotta say You inspired me !!
    i tryed to make such effect …but it was epic fail because of HUGE frame lag.
    But then I read your tut and it was better
    but then I expirienced an enlighment!

    because even if I put much more drop on your screen your script still suffer frame lag and hey I tryed another trick!
    I painted all drops on bitmap and put bmp on screen
    its realy efficient! Try it :)
    I think its called buffering …or such.
    sorry for my bad eng :)

    ( Reply )
  1. Arrow
    Gravatar

    Your Name
    October 13th