Create a Rain Effect in Flash Using ActionScript 3.0

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!

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!

Add Comment

Discussion 86 Comments

Comment Page 1 of 21 2
  1. axel says:

    ummm maybe its just me but i cant see the rain

  2. lawrence77 says:

    not so realistic…. :(

    But ok….

  3. MSFX says:

    some splashes would be nice, hard but nice ;)

  4. Sean says:

    Excellent. Well Done.

    Am trying it out now whilst looking at it raining outside

  5. jack says:

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

  6. TPN says:

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

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

  8. André says:

    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.

    • Alex says:

      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.

      • Ian Yates says:
        Staff

        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 :-)

      • André says:

        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.

      • Alex says:

        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.

      • André says:

        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. Nice effect and great tut Carlos.

  10. Franky says:

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

  11. Christo says:

    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!

    • André says:

      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 =)

      • dpcdpc11 says:

        hey Andre… this is exactly what I want to do so I’ve adapted this tutorial to make a snow effect, link here: http://www.bvbusinessconsulting.ro/snow_effect.rar
        but the problem is that the snow doesn’t fall smooth and I know how to work with tweens and all(TweenMax from greensock or Tweener from caurina), but I just have no idea how to implement a tween here… another option for making the snow fall smooth it would be to use some velocity based code, but unfortunately I don’t know how to do that either… maybe you could give me some help on this one??

  12. Diego SA says:

    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?

  13. Mike says:

    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.

  14. Erick says:

    you remind me of my fraternity brother

  15. CgBaran Tuts says:

    Great effect nice tutorial thanks

  16. Hi Carlos

    it’s really good

    keep it up………

    cheers
    satyaspb

  17. hey says:

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

  18. sandip kumar says:

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

  19. sandip kumar says:

    nice

  20. Jason says:

    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.

  21. May29 says:

    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?

  22. Saqib Butt says:

    hmmm great!!!

  23. anonymous says:

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

  24. aaaaa says:

    expecting identifier before lessthan?? help

  25. Sil3ntParadi9m says:

    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?

    • d Joyce says:

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

  26. Kieran says:

    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?

  27. katro says:

    I DID ITT!!!! YEEII!!

  28. ahmad says:

    Hmm…it’s great, cool animation

    thank for your tutorial

    I love it…^^

  29. uday says:

    hey great creativity. very nice

  30. james anderson says:

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

  31. goldfinger says:

    nice effect but i could’nt do it

  32. kruti says:

    not working….

  33. d Joyce says:

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

  34. Chris says:

    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 :)

  35. Kenneth says:

    sorry, but i got something like this
    The class or interface ‘drop’ could not be loaded.

  36. sanjeev kumar says:

    it is very nice

  37. dpcdpc11 says:

    first thanks for this great tutorial… second I need a bit of help…
    I took a step further the tutorial and created a ‘snow effect’… but the problem is that even though I slowed down the speed of the snow flakes, they are not falling smooth enough… what can I do to make them fall smooth?

    here is the link to the source code: http://www.bvbusinessconsulting.ro/snow_effect.rar

  38. Shimi says:

    very nice tutorial…

  39. Shimi says:

    very nice tutorial…but not working

  40. Ayko says:

    The .fla do not open “format de fichier inattendu” .. :s

  41. Thanks for your work and sharing. :)
    Exactly what I was looking for…

  42. Tom says:

    Can any one give a link for this rain effect? to download

  43. Ryan says:

    Being new to actionScript I was lost at step 6. What is a class? Does all this code go into a separate file? Do all the steps combine into one piece of code up to step 17 which is separate too?

  44. mobiles says:

    its very nice i like it

  45. robert says:

    Hi Ryan,

    Cool tutorial, thanks. I have one question, if you don’t mind. How can i stop the rain? :(
    I’ve tried to put rain.stop() even that i know that stop() function on frame is not working in AS3
    Any clue?

    Thanks in advance,

  46. Robert says:

    Sorry, i was reffering to Carlos, althought he wrote the code.
    Sorry again.

  47. xuan says:

    out of the topic, but I was surprised with the picture you’ve selected. It’s my hometown :)

  48. Adem says:

    To vastly speed this up, remove the gradient fill from the rain drop movieclip!

    Cheers,

    Adem

  49. Herman says:

    Very Nice, I am able to use it. But how can I make the rain effect as the background? at the moment I have a few layers and it’s on top of everything, on top of the text, I am working on a project and hope you can help me out as soon as you can by answering this question, thank you.

  50. Jacek says:

    Thanks a lot!

Comment Page 1 of 21 2

Add a Comment

To add a code snippet to your comment, please wrap your code like so: <pre name="code" class="html">YOUR CODE</pre>. You can replace the class name with "js," "css," "sql," or "php." If there are any "<" or ">" within your code, please search and replace them with: &lt; and &gt; respectively.