Tutorials Books Videos Forums

Change the theme! Search!
Rambo ftw!

Customize Theme


Color

Background


Done

Grassy Field: Case Study

by kirupa   | filed under Flash and ActionScript

As I was browsing through the forums, I noticed a really nice flash footer created by the moderator lostinbeta. In his footer, he has pictures of grass moving in response to the mouse. In short, the footer was cool and I wanted to create something like it! After a few hours of tinkering with Flash, I created something completely different (and CPU-intensive) that somehow ended up involving grass:

[ the above is an example of a grassy field created in Flash ]

If you are proficient with Flash, this tutorial will not teach you anything new or arcane. What you will learn is how to combine all of the bits and pieces of ActionScript you have accumulated into creating a nice animation. After all, isn't programming all about applying everything you know into a nice, final result?

If you are a beginner/intermediate user, dim the lights, strap on your seatbelt, and bring the popcorn. You are in for quite a ride through the dark alleys of Flash and beyond. Enough of me babbling, the tutorial starts now.

Creating a Grassy Field

The following instructions will help teach you how to create an interactive, grassy field:

  1. Create a new document in Flash MX by going to File | New. A new, blank Flash MX movie will be displayed. Set the width and height of the movie to 300 pixels by 200 pixels respectively.
  2. Now, we need to draw the grass. Click the Pencil Tool from your toolbox. Select a green line color and draw a smooth, curved line near the bottom of your Flash stage:

[ drawing a blade of grass ]

  1. Once the blade of grass has been drawn, select the blade of grass and press F8 (or go to Insert | Convert to Symbol). The Convert to Symbol dialog box will appear. Enter an imaginative name, select movie clip, and press OK. The blade of grass is now a movie clip.
  2. Select the movie clip you just created. In the Properties panel, give the movie clip the instance name grass:

[ give the movie clip the instance name 'grass' ]

Playing with Grass

You have created the blade of grass. What we want to do now is find a way to duplicate the blade of grass numerous times to create the illusion of a field. Not only will the blades of grass be duplicated, they need to be duplicated in random locations with random levels of transparency to create depth.

Duplicating Grass

Instead of copying and pasting the grass movie clip hundreds of times, you can use Flash to copy the movie for you. To duplicate the movie, first, right click on Frame 1 and select Actions. Copy and paste the following code:

for (i=0; i<300; i++) {

	_root.grass.duplicateMovieClip("movie"+i,i);

}

[ copy and paste the above code into the Actions dialog box ]

Making Grass Position and Visibility Random

Now that the duplicating portion of the animation is through, we need to work on placing the grass in random locations. We also need to account for depth, varying sizes, and visibility that occurs because of it.

Right click on the grass movie clip and select Actions. Copy and paste the following code into the Actions dialog box:

onClipEvent (load) {

	this._x = Math.round(-10 + Math.random()*350);

	this._xscale = (50+Math.random()*350);

	this._yscale = (50+Math.random()*150);

	this._alpha = (10+Math.random()*90);

	rxn = Math.round(2+Math.random()*4);

}

[ copy and paste the above code into the Actions dialog box ]

Don't worry if all of this seems confusing. I will explain in detail what the lines of code accomplish.

Making the Grass Move

If you previewed your movie, you will see a nice field of hundreds of grass blades. In their current form, while nicer than what we created a few minutes ago, the grass is lifeless and static.

It is time to make the grass move:

  1. Right click on the grass movie clip and select Actions. The actions dialog box will appear with the code you pasted from above.
  2. Now, make sure your Actions dialog box is set to Expert Mode. Press Ctrl + Shift + E or press the little icon in the top-right corner of the Actions dialog box and select Expert Mode:

[ ensure you are in Expert Mode ]

  1. Once you have selected Expert mode, place your cursor after the last line and press Return. Copy and paste the code from the following box into your Actions Dialog box (after the first section of code):
onClipEvent (enterFrame) {

	x = (_root._xmouse+50)/rxn;

	this._xscale = -x;

	this._x -= x/10;

	pos = this._x;

	if (pos<-50) {

		this._x += Math.round(290+Math.random()*100);

	}

}

[ copy and paste the above code into the Actions dialog box ]

Save the animation and preview the animation by going to File | Publish Settings | HTML. Your animation should have grass and basically mimic the animation you saw above.

Why Does the Animation Work?

I believe that Flash programming is not about simply copying and pasting code. I think that you should understand the reasoning behind the code so that you can apply what you learned to create something even more cooler than boring grass moving across a field. The following sections will help you to learn how all the pieces of the code work.

Duplicating Grass

If you recall, we started off with only one blade of grass. Yet, in our animation, hundreds of blades of grass are competing for space on the screen. The solution lies in a line of code involving duplicateMovieClip.

The duplicateMovieClip action was included in the code pasted in Frame 1. The code that you pasted in Frame 1 is:

for (i = 0; i < 300; i++) {
  _root.grass.duplicateMovieClip("movie" + i, i);
}

Now, let's dissect the above lines of code and translate them into English! The first line is the iteration method that sets the duplicating process in motion. An iteration method is anything that creates a loop for a definite period of time until the loop is stopped.

for (i = 0; i < 300; i++) {
  _root.grass.duplicateMovieClip("movie" + i, i);
}

For tells Flash to begin looping. i=0 sets the initial value of i to zero. i < 300 tells Flash to loop whatever action is contained within the loop (the code in gray) until the variable i almost reaches 300. If we started out with i equaling 0, and we tell Flash to loop until i reaches 300, how does i ever go from 0 to 300? The answer lies in the code i++. i++ is called an "incrementer" because it increments the value of the variable i by a certain amount. In this code, the certain amount is 1.

The second part of duplicating grass is actually duplicating the grass! The line of code we will be focusing on is the following:

for (i = 0; i < 300; i++) {
  _root.grass.duplicateMovieClip("movie" + i, i);
}

The basic syntax for duplicating a movie clip goes something like this:

myMovieClip.duplicateMovieClip(newname, depth);

Here's what each word in the above line of code represents:

Strange how three simple lines of code can be elaborated to fill up a few pages of text. I hope the above explanations helped you to understand how and why the grass movie gets duplicated.

Making the Grass Unique

When you have 300 pieces of grass being repeated in a small space, it becomes difficult to make it seem like each blade of grass is unique with its own special characteristics. Thanks to Flash's random function, it becomes possible. The first four lines in the onLoad section ensure that the grass is different each time it is looped:

this._x = Math.round(-10 + Math.random() * 350);
this._xscale = 50 + Math.random() * 350;
this._yscale = 50 + Math.random() * 150;
this._alpha = 10 + Math.random() * 90;

The lines are fairly self-explanatory. In the first line, I randomly place a grass movie clip in an area encompassing -10 pixels and 350 pixels. I go a little beyond the stage with -10 pixels to ensure continuity. When you look at a field, you see grass gradually appear; there is no fine line between where the field starts and the road/mud ends.

The _xscale and _yscale randomly scale the width and height of the movie clip to create the illusion of depth and varying sizes. The _alpha value makes each blade of grass have a different level of transparency. Because there are many individual blades of grass, having partially transparent blades of grass creates a nice blurred effect.

Moving and Looping the Grass

Moving and looping the grass is slightly more complicated than the remaining sections. Here are the lines of code that make the grass move:

x = (_root._xmouse + 50) / rxn;
this._xscale = -x;
this._x -= x / 10;
pos = this._x;
if (pos < -50) {
  this._x += Math.round(290 + Math.random() * 100);
}

In the first line, I declare a variable x that will scale the grass movie clip as the mouse cursor moves to the right. The second line ensures that the value of x is applied to the _xscale of the grass clip. Because I want the scaling to be opposite with that of the mouse motion, I add a negative in front of the x variable in the second line.

The code in bright blue involves the actual movement of the grass. The variable x makes yet another appearance. The position of the grass will be decremented by the value of x divided by 10. It is being decremented because the grass is moving left. Remember, in the co-ordinate plane, the further you move left on the x-axis, the less the number actually becomes.

The rxn variable in pink color is a value generated randomly from the last line of the onLoad action. That value specifies how quickly the value of x will react to mouse movements. The higher the value of rxn, the more sluggish the movement will be. The lesser the value of rxn, the more nimble the movement will be.

Once the grass moves outside of the stage area, it becomes useless. Well, useless until we make it appear again. Notice the if statement in blue. If the blade of grass moves 50 pixels beyond the left edge of the stage, it will randomly be brought back at a location on the right to create a seamless, never-ending field of grass!

Just a final word before we wrap up. What you've seen here is freshly baked content without added preservatives, artificial intelligence, ads, and algorithm-driven doodads. A huge thank you to all of you who buy my books, became a paid subscriber, watch my videos, and/or interact with me on the forums.

Your support keeps this site going! 😇

Kirupa's signature!

The KIRUPA Newsletter

Thought provoking content that lives at the intersection of design 🎨, development 🤖, and business 💰 - delivered weekly to over a bazillion subscribers!

SUBSCRIBE NOW

Creating engaging and entertaining content for designers and developers since 1998.

Follow:

Popular

Loose Ends

:: Copyright KIRUPA 2026 //--