Archive for the ‘Flash Tutorial’ Category

Smooth Scrollbar Flash Tutorial

May 10th, 2011 | 15 Comments

So much content and so little space in which to display it.

In this tutorial, I want to discuss the basics of creating scrollable content in ActionScript 3. In our examples, scrollable content will include much more than simple scrollable text fields. For our purposes here, we want to learn how to create scrollable content that can include images, movie clips, and more.

Step 1 – Store Your Content in a Movie Clip

In order to display the power of our custom scrollbar, I am going to include text and Movie Clips within our scrollable content. Once you've built out your content, select all of it and go to Modify > Convert to Symbol. Set the symbol type to "Movie Clip", and call it "mcContent" (or something similar). IMPORTANT: If you want your calculations to work properly, be sure to set the registration point to the upper-left corner of your Movie Clip when you create it, like so:

Registration Point

After creating the Movie Clip, select it on the stage, go to the Properties Panel, and give it an instance name of content_mc. On the stage, your content will look something like this:

Scrollbar Flash

 

Notice that our content, extends past the bottom of the stage: hence our need for scrollable content.

Step 2 – Mask Your Content

The next step is to create a mask that reveals only the area where you want the content to be visible. In this case, our mask will be a simple rectangle with a fill and no stroke that takes up most (but not all) of the height of the stage itself. Be sure to create your mask on a new layer directly above your content layer. I like to use a bright green fill color for my masks, but that's just a personal preference. It doesn't matter what color you use.

After you draw your mask rectangle, select it and convert it to a Movie Clip Symbol. Your mask should look like this:

mask

As a reminder, the mask represents the area of your content that you actually want to be visible. Once the mask is applied, everything outside of the mask will be invisible.

Before applying the mask, double-check to make sure that your mask Movie Clip is on its own layer directly above the layer that contains the content you want to mask. Then, right-click on the layer that contains your mask and click on the "Mask" option. If done properly, the green rectangle should disappear, and you should see only the content that was inside the rectangle, like so:

 

Notice that all of the excess content is now invisible. Only the content that was behind the mask is visible. Now, in order to scroll the content, we just need to animate it behind the mask in response to interaction with a scrollbar.

Step 3 – Build the Scrollbar

Your scrollbar will contain two elements nested into one Movie Clip: the background and the scroller. Each of these items are simple rectangles. Here's what I came up with:

 

 

Like I said, two rectangles. Pretty simple. You can spice it up if you like, but I'm going to stick with the minimalist look for now. Either way, you will end up with two separate Movie Clips: one for the background of your scrollbar and one for the draggable handle that you will use to do the actual scrolling. Give this handle an instance name of scroller_mc. Then select both the scroller and the background and hit F8 to combine them into a single scrollbar Movie Clip. Give this Movie Clip an instance name of scrollbar_mc.

Step 4 – Dragging the Scroller

Your next task is to determine how far up and down your scroller will be able to move. When you drag the scroller, it's obviously not going to move left to right, but you need to figure out how far up and down it will move if you want everything to function properly. To figure this out, double-click on your scrollbar to go into the Movie Clip. Inside the Movie Clip, you should have two more Movie Clips: the background and the scroller. If you placed your scroller at it's beginning location, as in the image above, then you should already be able to determine its beginning y-coordinate. Simply click on the scroller and look at the y-coordinate shown in your Properties panel. In my case, it said 2.95 for the starting y-coordinate. But I want a nice whole number, so I changed the y-coordinate to 3. Whatever number you end up with here, write it down. In fact, go ahead and write down the x-coordinate, too, because you will need it in a few minutes. My (x,y) coordinates for the starting location work out to (4,3).

Next, select your scroller and drag it down to the lowest possible point within the bounds of your background rectangle. This time, you will only need the y-coordinate, so take note of it. In my case, the y-coordinate works out to 312. Your scroll range (the range you'll be able to drag the scroller up and down) will be the different between the ending y-coordinate and the first y-coordinate you wrote down. In my case, the scroll range works out to 312 - 3 = 309. So I should be able to drag my scroller up and down within a range of 309 pixels. So, how do we implement this in ActionScript? Easy!

First of all, move your scroller back to its original position. Then go back to your main timeline, create a new layer, rename the layer Actions, and with frame 1 of that layer selected, hit F9 (or Option+F9 on a Mac) to open up your Actions panel. Enter the following code:

var rect:Rectangle;

scrollbar_mc.scroller_mc.buttonMode = true;
scrollbar_mc.scroller_mc.addEventListener(MouseEvent.MOUSE_DOWN, dragIt);

function dragIt(e:MouseEvent):void {
	rect = new Rectangle(4, 3, 0, 309);
	scrollbar_mc.scroller_mc.startDrag(false, rect);
	stage.addEventListener(MouseEvent.MOUSE_UP, dropIt);
}

function dropIt(e:MouseEvent):void {
	scrollbar_mc.scroller_mc.stopDrag();
}

The first line of code creates a variable where we will store a rectangle that will determine the draggable bounds of our scroller. This variable is being created outside of all functions, because once we actually create the rectangle, we will need to access its properties in more than one place. More on that later.

The next line sets the buttonMode property for the scroller Movie Clip to true. This will cause the scroller to behave like a Button in that it will cause your mouse cursor to turn into the hand cursor when you hover over it.

The third line adds a MOUSE_DOWN listener to the scroller. Think about how a scrollbar works. When you press your mouse button down on the scroller, that's when you want it to start dragging, so that's when our code triggers the "dragIt" function.

Inside the dragIt function I've created a rectangle object. This rectangle will not be drawn on the stage; it will simply be used to determine the bounds of our draggable area for the scroller. When the "new Rectangle()" method is called, you'll notice I entered four different numbers. The first two numbers (4 and 3) determine the x,y coordinates of the rectangle. This should be the same as the beginning x,y coordinates that you wrote down earlier for your scroller Movie Clip. The next two numbers (0, 309) determine the width and height of the rectangle. Since we don't want to be able to drag the scroller left and right, the width of our rectangle is 0. The height of my rectangle, as calculated before, is 309. As you can see, this rectangle was created and stored in a variable called rect.

After creating the rectangle object, we are calling on the startDrag() method and passing in two parameters. The first parameter determines whether or not the center of the object you're dragging will snap to where your mouse cursor is. We don't want this to happen, so we entered false. The second parameter is simply the variable name we gave to the rectangle we just created. Basically, we're telling the startDrag() method to use rect to determine the draggable boundaries of our scroller.

After creating the drag functionality, you need to create the functionality to stop dragging. Notice that I've added this particular listener to the stage instead of to the scroller itself. If you add the MOUSE_UP listener to the object itself, then it will only be triggered if you're still hovering over the Movie Clip when your mouse cursor is released. Adding the listener to the stage, on the other hand, assures us that no matter where our mouse cursor is when we release the mouse button, the dropIt function will be called, and dragging will cease.

Step 5 – Making the Scrollbar Work

In order for your scrollbar to function properly, there is a little bit of math involved. The y-coordinate of your content is going to change in response to the y-coordinate of your scroller. As you drag your scroller up and down, your content will move up and down in the opposite direction. But how much will it move?

Instead of thinking in terms of the number of pixels moved, let's think in terms of percentages. This will make things much easier. For example, if you have dragged your scroller 50% of the way down its scrollable range, then you want your content to move up 50% of its total range. When you think in terms of percentages, this whole solution become easier to wrap your head around.

So, in order to determine a percentage for your scroller, you need two numbers:

  1. The total range of movement for the scroller.
  2. The current y-coordinate within that range, adjusted for it's starting position.

The reason we need to adjust for the starting position is because our scroller doesn't start off at a y-coordinate of 0. In my file, it is at a y-coordinate of 3 within the scrollbar Movie Clip. Let's take a look at a beautifully-rendered Photoshop illustration of what we're doing here:

Scroller Example

Okay, so it's not technically a percentage we're calculating; it's more of a ratio. But you get the point. According to the example above, the current position of the scroller (adjusted for its minimum y-coordinate) is roughly 49.5% of the way down its total range of movement. As a response, we want the content to move to a position 49.5% of the way up its own range of movement, so we'll simply use the same ratio (0.495) to calculate where it needs to be.

Now that I've properly over-explained everything, let's take a look at the final code. Before entering the following code, be sure to give an instance name to the Movie Clip you're using to mask your content. I've given mine an instance name of mask_mc.

var rect:Rectangle;
<strong>var scrollerMinY:Number = scrollbar_mc.scroller_mc.y; var contentMaxY:Number = content_mc.y; var padding:Number = 40;</strong>

scrollbar_mc.scroller_mc.buttonMode = true;
scrollbar_mc.scroller_mc.addEventListener(MouseEvent.MOUSE_DOWN, dragIt);

function dragIt(e:MouseEvent):void {
	rect = new Rectangle(4, 3, 0, 309);
	scrollbar_mc.scroller_mc.startDrag(false, rect);
	stage.addEventListener(MouseEvent.MOUSE_UP, dropIt);
	<strong>scrollbar_mc.scroller_mc.addEventListener(Event.ENTER_FRAME, scrollIt);</strong>
}

function dropIt(e:MouseEvent):void {
	scrollbar_mc.scroller_mc.stopDrag();
        <strong>scrollbar_mc.scroller_mc.removeEventListener(Event.ENTER_FRAME, scrollIt);</strong>
}

<strong>function scrollIt(e:Event):void {</strong>
<strong> var scrollerRange:Number = rect.height; var contentRange:Number = content_mc.height - mask_mc.height + padding; var percentage:Number = (scrollbar_mc.scroller_mc.y - scrollerMinY) / scrollerRange; var targetY:Number = contentMaxY - percentage * contentRange; content_mc.y = targetY; }</strong>

Once you have added the code in bold, you should have a working scrollbar, Flash style!

Hopefully, most of this code speaks for itself, but there are a couple things worth pointing out. First of all, you'll notice a variable I created called "padding". Sometimes, when you create your own custom scrollbar, the content doesn't always scroll up as far as you like when you drag the scroller all the way to the bottom. The padding variable adds a little bit more room to the total range of movement for the content, as seen in the scrollIt() function. The value entered here is completely optional, depending on how your text looks when scrolled.

Also, notice that we've added another line of code inside the dragIt() function. As soon as we start dragging the scroller, this line of code triggers an ENTER_FRAME event, which causes the scrollIt() function to run over and over again at the current framerate. That's how we get the smooth scrolling as we drag up and down. Also, since we've created this event listener, we need to delete it when we're done dragging. This is done in the dropIt() function.

Finally, inside the scrollIt() function, once we calculate the percentage that we discussed before, we use that percentage to place the content where it needs to be. We do this using the following calculation:

contentMaxY - percentage * contentRange

Multiplying the percentage by the contentRange gives us how far the content needs to be moved. This number is subtracted from the maximum y-coordinate of your content to properly offset it.

Here is your final result:

Click here to download the source files

Flash Tutorial – Fake 3D Extrusion

May 6th, 2011 | 2 Comments

A couple years ago, I accidentally discovered method for giving Flash text an extruded, 3D look, and it's insanely easy to do.

Step 1 - Create Some Text – Easy enough, right? In this case, I want to put a gradient on the text, so to keep things simple, I'm just going to break the text apart by going to Modify > Break Apart, or by hitting Ctrl+B on the keyboard. (Make sure everything is spelled correctly first. You can't edit the text after you do this.) This will break your text field up into multiple single-character text fields, so you'll need to break apart a second time in order to get the raw shape that we're looking for. Broken apart, your selected text should look like this:

Step 2 - Color Your Text – I'm going to apply a simple, top-to-bottom gradient to make our text a little more interesting. To do this, make sure your text is selected and open the Color panel (Window > Color). Click on the paint bucket icon in the Color panel to make sure the fill is selected, and then change the drop-down menu from "Solid color" to "Linear gradient." Click on the left handle and select a bright red color, then select the right handle and choose a darker red, like so:

By default, you may notice that the gradient on your text is moving from left to right. I want it to move from top to bottom. Select the Gradient Transform Tool, which is grouped with the Free Transform Tool, and select the first letter. Use the rotate and resize handles to transform your gradient so that it's moving from top to bottom. Repeat this for all letters until you have something like this:

Step 3 - Movie Clipify Your Text – Switch to your selection tool (keyboard shortcut = V), and select all of your text. Hit F8 to convert it to a Movie Clip, and set the registration point to the center.

Step 4 - Duplicate and Relocate – With your Movie Clip selected, hit Ctrl+C (or Cmd+C on a Mac) to copy your text, and then hit Ctrl+Shift+V (Cmd+Shift+V on a Mac) TEN TIMES to paste ten more copies of your text right on top of the original copy. Since they're all copied to the same place, it will still look like a single text field, but we're about to change that.

Now we want to change the Z coordinate of each of our Movie Clips. The Z coordinate determines how far the text is away from our virtual camera, or how far back it is in 3D space. For our purposes here, we want each successive Movie Clip to be a little further back in space.

Start by selecting all of your Movie Clips, and the use the Distribute to Layers command in the Modify > Timeline menu. This will send each copy of your text to its own layer, which will make it easier to edit individually.

Lock the topmost text layer–this one is going to remain as is. Then, one layer at a time, starting with the second text layer, change the z-coordinate so that each successive layer is 10 pixels further back than the one in front of it. The z-coordinate can be changed in the Properties panel under the "3D Position and View" settings. So your topmost text layer will have a z-coordinate of 0. The second layer will have a z-coordinate of 10. The third will be 20, and so on. When you're done, your stage should look something like this:

Not quite what we're going for, but we're getting much closer.

Step 5 - Use Brightness to Add Depth – Do the following for all of your text Movie Clips EXCEPT FOR THE ONE ON TOP:

  1. Select the Movie Clip
  2. In the Properties Panel, under Color Effect, change the Style from "None" to "Brightness."
  3. Drag the brightness slider to the left to darken it. I've chosen a value of -33%.
  4. Repeat for the next Movie Clip.

Once you're done with this step, your text should look like this:

Much better!

Step 6 - Movie Clipify – Unlock all of your layers, select all of your text Movie Clips, and hit F8 to convert all of your Movie Clips into one container Movie Clip. Once you do this, you'll see a little bit of magic occur. After everything has been placed into this container Movie Clip, select the Movie Clip and start dragging it around the stage. You'll see that no matter where you move it, the text seems to be disappearing towards the center of the stage. To customize this look further, select the Movie Clip, go to your Properties Panel, and under the 3D Position and View section, you will see options for changing the Vanishing Point (highlighted in the picture below).

By default, the vanishing point is in the center of the stage, but if you play around with these values, you can change the way your 3D text is displayed. In the following animation, I've simply increased the y-coordinate of the vanishing point and then tweened the container Movie Clip across the stage. Not bad for a quick hack job!

Note: If you notice a stair-stepping effect on the "extruded" text, you can smooth it out by decreasing the z-distance between each Movie Clip. Instead of increasing each z-coordinate by 10, try 5 or even less until you get the effect you're looking for.

ActionScript 3 Tutorial – Tweener Transitions

April 26th, 2011 | 12 Comments

I recently posted a couple of ActionScript button tutorials that made use of the Tweener class instead of the traditional Tween class, so I thought it would be appropriate to talk a little more about the Tweener class and discuss why and how to use it.

Tween vs Tweener

It doesn't take a Flash developer long to discover what a pain the traditional Tween class can be. Often for seemingly unknown reasons, animations created using the Tween class will just stop playing right in the middle of a transition. This is usually due to ActionScript's method of garbage collection, and extra code is often needed to alleviate the issues. In other words, sometimes Flash thinks you're done using a Tween before it's even finished animating, so it just throws the Tween away. Thanks, ActionScript, but no thanks! Why deal with these pesky annoyances when there's a much easier class to use?

Introducing the Tweener class, an open-source class for creating ActionScript animations that doesn't have all the messy garbage collection problems. In other words, the Tweener class will actually wait for your animations to finish before deciding they're not needed any more. A novel idea!

Installing Tweener

If you've never installed your own class before, I'll give you a quick rundown of what I do.

1. Create a folder. I keep all of my external classes in a folder on my desktop called "as". If you're a neat freak who doesn't like a messy desktop, then you can place your ActionScript folder wherever you wish, but don't come crying to me when you can't seem to find where you placed it. (Because then I'll make fun of you for not knowing how to use your computer's search features.)

2. Download the class files. The class files for the Tweener class can be found at Google's code repository, here. Click on the "download" tab at the top of the page, and you'll see a list similar to this one:

Notice that Tweener is available for both ActionScript 2 and ActionScript 3, so make sure you grab the right version. The version I'll be using is the ActionScript 3 version. Select the latest stable version, and download the appropriate zip file–in this case, the tweener_1_33_74_as3.zip file.

3. Install the Tweener Class. This part is easy. Simply unzip the files you just download and then copy the caurina folder (which contains the Tweener class) into the ActionScript folder that you created earlier. Then open up Flash and go to Edit > Preferences.

Click on the ActionScript category on the left side of the Preferences dialog, and then click on the button for ActionScript 3.0 Settings. Under the "source" section, we can tell Flash where to look for classes that aren't included in the default Flash package. Next to "Source path:", click on the plus sign icon. This allows you to create a new path for Flash to include.

Clicking the plus sign will create a new entry. Now we need to point that entry to the right place, so click on the folder icon to browse for the folder(s) you want to include. In this case, we want to include more than just the "caurina" folder. If you don't want to go through this process every time you download a new class, it would be best to simply include the entire "as" folder that you created before. Notice that my path includes a subfolder called "3". I have two separate folders: one for ActionScript 2 classes and one for ActionScript 3.

Using the Tweener Class

Now that you've installed the Tweener class, let's take a look at just how easy it is to use. First of all, the Tweener class must be imported using the following line of code:

import caurina.transitions.*;

This will import all of the classes associated with the Tweener class. If this import doesn't work, then you need to double-check to make sure that your "caurina" folder is inside the "as" folder that we discussed before. Also, double check your ActionScript settings to make sure you entered your Source Path properly.

As for the Tweener code itself, you will hopefully appreciate its beautiful simplicity. Consider the following example:

Tweener.addTween(square_mc, {"x":100, transition:"linear", time:1, delay:1});

It may seem complicated at first, but if you take a close look, it's pretty easy to figure out.

To create a new Tween with the Tweener class, you will use the Tweener.addTween() method. The first parameter sent to this method (in this case, square_mc) is the name of the object you want to apply the animation to. Here, we're assuming that there's a MovieClip on the stage with an instance name of square_mc.

The second parameter for the addTween() method is an object contained within curly brackets that consists of numerous property/value pairs. In this example, you can see that we're going to animate the "x" property of the square MovieClip. The starting value for this property will be whatever its current "x" coordinate is on the stage. It will animate until it reaches an "x" value of 100.

Note that you can include multiple properties here, which is another fantastic advantage to the Tweener class. With the traditional Tween class, if you wanted to animate both the x and y coordinates, for example, you would have to create two separate Tweens for it. With the Tweener class, on the other hand, you simply add another property/value pair within the curly brackets. So if I wanted to animate both x and y, I could enter the following:

Tweener.addTween(square_mc, {"x":100, "y":100, transition:"linear", time:1, delay:1});

You can animate any number of properties all at once simply by including them within the curly brackets. As you can see, this is a very flexible class. (Now you can see why I never use the Tween class anymore!)

The next property–the transition property–determines how easing is applied to your animation. The Tweener class contains a more flexible array of easing options than the traditional Tween class, which we will discuss shortly.

The time property determines the duration, in seconds, of the transition. In this case, the new Tween will last 1 second.

The delay property is an optional property that allows you to delay the start of the transition. In this example, the animation waits one second before starting. This property can come in very handy if you have multiple animations that you want to occur in sequence. For example, if you want to play three 1-second animations, one after the other, then you would set the delay for the first Tween to zero, the second Tween to one, and the third to two, like so:

Tweener.addTween(square_mc, {"x":100, transition:"linear", time:1});
Tweener.addTween(square2_mc, {"x":100, transition:"linear", time:1, delay:1})
Tweener.addTween(square3_mc, {"x":100, transition:"linear", time:1, delay:2})

Note that there is no delay set for the first Tween here. The delays are only set for the second and third animations.

Tweener Transitions

As I mentioned, the Tweener class contains more options for easing than the easing classes associated with the traditional Tween class. Here are a few of my favorite options for use with the transition property:

  • "linear" - This option is the most basic. With the "linear" option, no easing is applied to your animation.
  • "easeInSine" - This is a basic "ease in" option. The animation starts off slow and speeds up towards the end, like an accelerating car.
  • "easeOutSine" - The basic "ease out" option. The animation starts off quickly and slows down towards the end, like a car hitting the brakes and coming to a stop.
  • "easeInOutSine" - This option gives a smooth, gradual start and end to the animation.
  • "easeOutElastic" - This is more of a rubber-band-like animation. Just try it. It's easier to watch than to explain.
  • "easeOutBounce" - Again, just try it.

Overwhelmed? Afraid you're not going to remember all of these easing options? Don't worry about it. There is a very useful Tweener Transitions cheat sheet available that has graphs of all the transitions and how they behave. I keep this cheat sheet pinned to my corkboard. It would behoove you to do the same.

Sample Animation

Consider the following code:

import caurina.transitions.*;
import flash.events.MouseEvent;

square_mc.buttonMode = true;
square_mc.addEventListener(MouseEvent.CLICK, rotateIt);

function rotateIt(e:MouseEvent):void {
   square_mc.rotationX = square_mc.rotationY = square_mc.rotationZ = 0;
   Tweener.addTween(square_mc,{"rotationX":360, "rotationY":360, "rotationZ":360, time:1, transition:"easeInOutSine"});
}

This code sets up a Movie Clip called square_mc as a button that rotates around its x, y, and z axes when clicked. Inside the rotateIt function, notice that I'm resetting the rotationX, rotationY, and rotationZ properties before actually doing the rotations. Otherwise, the animation will only work the first time you click on the Movie Clip. Here's the final result:

Click here to download the source file.

 

Tutorial – Object-Oriented Buttons in ActionScript 3

April 22nd, 2011 | 6 Comments

For some people, creating a separate class for a simple button is overkill. However, if you find yourself  reusing the same kind of button over and over, it may behoove you to apply some simple object-oriented ActionScript.

In the last tutorial, I demonstrated how to create an ActionScript 3 Button that didn't rely on the timeline for its animated mouseovers. We're going to create a similar button for this tutorial, but this time, we're going to store the code for the button in a separate ActionScript Class. Let's get started.

Step 1 - Create Your Button Graphics. I'm going to keep things simple and create the same basic button that we discussed in the previous tutorial. Keep the following things in mind as you're preparing the graphics for your button:

  1. Convert your graphics to a Movie Clip symbol with the registration point in the center. As we've discussed before, Movie Clip symbols are much more flexible than Button symbols.
  2. Within your Movie Clip button, put your background graphics inside its own Movie Clip so we can animate the background separate from the text.
  3. Make your text field dynamic (or "TLF Text" if you're using CS5) and embed all uppercase, lowercase, numerals, and punctuation (and anything else you might need) for your font. Give your text field an instance name of label_txt. Later, you will set the text of your button in ActionScript, and you will refer to this instance name in order to do that.

Keep in mind that this time around we're not going to give our Movie Clip button an instance name. Since you're going to attach it to the stage using ActionScript, you just need to create your Movie Clip and then delete it from the stage. (Don't worry, it's still available in your Libary.)

Step 2 - Export for ActionScript. Your next step is to set up your button so that you can access it and attach it to the stage in ActionScript. Find your Movie Clip in the Library Panel, right-click on it, and click on Properties. You will see the following dialog. (If you don't see all the options below, click on "Advanced" in the Symbol Properties dialog.)

Check the "Export for ActionScript" checkbox. This will automatically cause the "Export in frame 1" checkbox to be checked as well, which is what we want.

Flash will automatically populate the field for the Class name with whatever name you gave to your Movie Clip symbol. Edit this name to make sure that the first letter of the class name is a capital letter. The name I'm using here is MCButton. By convention, all class names are capitalized. The name you enter here is very important, so make a note of it. This is the name you will give to your Class when you create it. It's also the name you will use in your ActionScript to attach the Movie Clip button to the stage.

Leave the rest of the options at their default and click "OK" to apply the changes. When you click "OK", a dialog box will pop up and warn you that it can't find the class name you entered. Well, that's what we're about to create, so just click "OK" again, and let's move on.

Step 3 - Create Your MCButton Class. If you've never created your own ActionScript class before, don't worry–it's not as complicated as it sounds. An ActionScript class is simply an external text document that contains ActionScript code in it. The only major differences with external classes is that they have to be structured a certain way, and they require you to import every class you refer to.

To create a class in Flash, go to File > New, and in the popup dialog, select "ActionScript 3.0 Class".

If you're using Flash CS5, then when you click on "OK", you will get another prompt asking you for the name of your class. This needs to be identical to the Class name you assigned to your Movie Clip when you exported it for ActionScript–in this case, MCButton. In CS5, once you enter this class name, your ActionScript class will automatically be set up with the appropriate skeleton code, shown below.

package  {

	public class MCButton {

		public function MCButton() {
			// constructor code
		}

	}

}

If you have an earlier version of Flash, it will take you directly to your AS3 file. Simply copy and paste the code you see above, and then we'll all be on the same page.

Before we move any further, go ahead and save your class file. There are only two things you need to know about saving your class:

  1. Your file name needs to be identical to your class name, capitalization and all.
  2. The file name for an ActionScript class contains the .as extension.

Armed with this knowledge, go to File > Save, and save your file as MCButton.as. (Note: One minor annoyance I've found with editing ActionScript from within the Flash authoring environment is that you don't get popup code hints until you save your ActionScript file; so that's usually the first thing I do when working with external classes.)

Let's take a look at the code we have so far:

In line one, we're putting all of our code within a package. Packages are a little beyond the scope of this tutorial, so for our purposes here, I'll just say that all of our classes will be contained within a package like this.

Within the package declaration is the class declaration. This class is public, which simply means that you can freely access this class from within other classes or other Flash files.

The class declaration as we see it above is still missing a little something. Remember that we're assigning a Movie Clip to this class, and every instance of MCButton that we create is going to require an instance of that Movie Clip. So, in order for this class to be fully effective, it would be nice if our class had all the same properties and methods of the MovieClip class. Well, this can be accomplished through inheritance. All we need to do is tell Flash that we want this class to extend the functionality of the MovieClip class, like so:

package  {

	import flash.display.MovieClip;

	public class MCButton extends MovieClip {

		public function MCButton() {
			// constructor code
		}

	}

}

Notice that two things have changed here. The first change is that we now have an import statement just inside the package declaration. As I mentioned before, every class you reference from within your ActionScript needs to be imported, and our imports will occur before our class declaration but still inside the package.

The second change can be seen within the class declaration. We have added the phrase "extends MovieClip". This tells Flash that we want to inherit all of the functionality of the MovieClip class in addition to whatever other functionality we add within our class. Pretty cool, huh?

Within the class declaration is the constructor function. A constructor is a function that is called automatically whenever a class is instantiated. In other words, if you want something to happen with your button as soon as you place it on the stage, this is where you would put that code. Notice that the constructor function has the exact same name as the class itself. This is required for a constructor function; in fact, that's how Flash knows that it's your constructor. Every ActionScript class will have a constructor, but it won't always have code within it. If there's nothing that needs to happen when you place your constructor on the stage, then you would just leave your constructor empty. For a Movie Clip button, however there are a couple things we need to include here. For example, whenever we place our buttons on the stage, we want them to act like buttons. In other words, we need to add our mouse listeners here, because as soon as we instantiate our buttons, we want them to start listening  for mouseovers and any other events we might need.

Here is our updated constructor function:

public function MCButton() {
	// constructor code
	this.buttonMode = true;
	this.addEventListener(MouseEvent.MOUSE_OVER, hover);
}

First of all, since you're using a Movie Clip symbol and treating it like a button, you need to turn buttonMode on. Now, when you hover over it, you will see the hand cursor that you expect to see when hovering over a button or a link. Secondly, you're creating your mouseover event using the addEventListener() method.

Remember that when you're dealing with external classes, you must import every single class you use within that class. (Anything that starts with a capital letter is usually a class.) Since we're referring to the MouseEvent class here, be sure to add the following code just below where you imported the MovieClip() class:

import flash.events.MouseEvent;

If you tried to test everything right now, you would get an error, because our event listener is currently referring to a function that doesn't exist yet: namely, the hover function. Let's create that now. Enter the following code just below the closing curly bracket of the MCButton constructor function, but still within the curly brackets for your package and class:

private function hover(e:MouseEvent):void {
	this.removeEventListener(MouseEvent.MOUSE_OVER, hover);
	this.addEventListener(MouseEvent.MOUSE_OUT, out);
	Tweener.addTween(this.bg_mc, {scaleX:1.5,time:0.5,transition:"easeOutElastic"});
}

private function out(e:MouseEvent):void {
	this.removeEventListener(MouseEvent.MOUSE_OUT, out);
	this.addEventListener(MouseEvent.MOUSE_OVER, hover);
	Tweener.addTween(this.bg_mc, {scaleX:1,time:0.5,transition:"easeOutElastic"});
}

Once we hover over the button, we no longer need to listen for the MOUSE_OVER event, so inside the hover() function, remove this listener. Then, you will add the MOUSE_OUT listener, which will trigger the out() function, seen below the hover() function.

After adding the MOUSE_OUT listener, we're calling on the Tweener class (click here for more info) to animate the width of the bg_mc Movie Clip within our button. This (bg_mc) is the instance name I gave to the background of the button. And once again, since we're calling on an external class, it's time for another import statement, just below your last one:

import caurina.transitions.*;

Another thing you might have notice in your code is the constant use of the word this, which simply refers to the button object itself. When we reference the Tweener class, for example, you'll see that I have made a reference to this.bg_mc, which refers to the background Movie Clip within the current button Movie Clip.

Step 4 - Add an MCButton to the Stage. For all intents and purposes, you now have a fully functional ActionScript 3 class. Easy enough, right?

Jump back over to your FLA file, and if you still have a button on your stage there, get rid of it. We're going to add a button now using ActionScript.

Once your stage is clear, click on frame 1 in your timeline and hit F9 (or Option+F9 on a Mac) to open up your Actions Panel. Enter the following code:

var btn1:MCButton = new MCButton();
btn1.x = 150;
btn1.y = 50;
addChild(btn1);

To create a new button, the first thing you need to do is to create a variable in which to store it. This is taken care of in the first line, where you create a new instance of the MCButton() class and store it in a variable called btn1.

In the next two lines, set the x and y coordinates of your button (your coordinates might be different than mine), and then add your button to the stage using the addChild() method.

Voila! If you've installed the Tweener class properly (and entered the code correctly), then you now have your own object-oriented button class.

However, we're not finished yet. One of the advantages of this object-oriented approach is the ability to customize each instance of your button without having to enter a bunch of extra code.

Can you see something that could use some customization?

Step 5 - Changing Your Button Labels. As it stands, every button you place on the stage is going to have whatever default text you entered into your text label. Well, we didn't make our text field dynamic just for the fun of it, so let's take a look at how we can customize our labels.

The most obvious method is to customize your label within the ActionScript for your FLA file. So, instead of the above code, you would have something like this:

var btn1:MCButton = new MCButton();
btn1.x = 150;
btn1.y = 50;
btn1.label_txt.text = "home";
addChild(btn1);

The most dynamic way would actually be to create your text field dynamically from within your class file, but that's a little beyond the scope of this tutorial. For our purposes here, let's just stick with the code we have so far. So if you wanted three different buttons using your fancy new MCButton class, you might use the following code:

var btn1:MCButton = new MCButton();
btn1.x = 150;
btn1.y = 50;
btn1.label_txt.text = "home";
addChild(btn1);

var btn2:MCButton = new MCButton();
btn2.x = 150;
btn2.y = 100;
btn2.label_txt.text = "about";
addChild(btn2);

var btn3:MCButton = new MCButton();
btn3.x = 150;
btn3.y = 150;
btn3.label_txt.text = "contact";
addChild(btn3);

Now you have a fully functional, object-oriented, ActionScript 3 button that can be duplicated with only a couple lines of code. And just for your reference, here is the final ActionScript 3 class file:

package  {

	import flash.display.MovieClip;
	import flash.events.MouseEvent;
	import caurina.transitions.*;

	public class MCButton extends MovieClip {

		private var btnLabel:String;

		public function MCButton() {
			// constructor code
			this.buttonMode = true;
			this.addEventListener(MouseEvent.MOUSE_OVER, hover);
		}

		private function hover(e:MouseEvent):void {
			this.removeEventListener(MouseEvent.MOUSE_OVER, hover);
			this.addEventListener(MouseEvent.MOUSE_OUT, out);
			Tweener.addTween(this.bg_mc, {scaleX:1.5,time:0.5,transition:"easeOutElastic"});
		}

		private function out(e:MouseEvent):void {
			this.removeEventListener(MouseEvent.MOUSE_OUT, out);
			this.addEventListener(MouseEvent.MOUSE_OVER, hover);
			Tweener.addTween(this.bg_mc, {scaleX:1,time:0.5,transition:"easeOutElastic"});
		}

	}

}

And here's a look at the final output:

Related Post: ActionScript 3 Tutorial - Tweener Transitions

Tutorial – ActionScript 3 Buttons

April 19th, 2011 | 7 Comments

In a previous tutorial, I demonstrated how to create a Movie Clip button in Flash. Movie Clips are much more flexible than Button Symbols, so it often makes more sense to use a Movie Clip and treat it as a Button. However, even the previous tutorial was a little limited in its possibilities in that it still relied heavily on the Timeline. Today, I want to demonstrate how break free from the Timeline and create a truly dynamic button that can be reused with very few changes to the original. We're still going to create a Movie Clip button, but the functionality for this particular button will rest entirely in the ActionScript 3 code that we will apply to it.

Before we get started, let's take a look at the final result:

Creating the Button

For the purpose of this tutorial, I want to keep the button's text separate from its background. This will allow us to animate the width of the background without affecting the text.

Step 1 - Create the background. Let's keep it simple. Using the Rectangle Tool (keyboard shortcut 'R'), create a rectangle, applying whatever visual attributes you prefer. Switch to the Selection Tool (V) and hit F8 to convert the rectangle to a Movie Clip symbol. This Movie Clip will contain only the background for the button, so name it "btnBG" and set the registration to the center, like so:

(Note: If you want your button to expand out to the right instead of from the center, set your registration point to the left when converting your shape to a Movie Clip.)

Give your new background Movie Clip an instance name of "bg_mc". This is the name we will use to refer to the background in our ActionScript.

Step 2 - Label your button. Create a new text field using the Text Tool (T) and align it to the center of the button using the Align Panel. To make things really dynamic, make your text field dynamic. If you're using Flash CS4 or earlier, make your text field a Dynamic text field in the Properties Panel. If you're using CS5, you can use the new TLF Text property. With your text field selected, give it an instance name of "label_txt".

Step 3 - Embed Your Fonts. This is a very important step if you want your text to show up properly. With your text field still selected, click on the "Embed" button in the Properties Panel. In the popup, select Uppercase, Lowercase, Numerals, Punctuation, and any other options that you might end up using in your text field. Click "OK" to apply your changes.

Step 4 - Create your Movie Clip button. Using the Selection Tool (V), select both your button background and your text field and hit F8 to convert your graphics to a symbol. Again, set your registration point to the center, choose "Movie Clip" for the symbol type, and give it the name "mcButton". Select your new Movie Clip button and give it an instance name of "button_mc".

Coding the Button

Double check to make sure your instance names are all the same as mine. Once this is confirmed, create a new layer named "Actions", click on frame one of this new layer, and hit F9 (or Option+F9 on a Mac) to open up your Actions Panel. (Additionally, you can also access the Actions Panel from the Window menu.)

Add the following code to frame one of your Actions panel:

import caurina.transitions.*;
import flash.events.MouseEvent;
import flash.net.URLRequest;

button_mc.buttonMode = true;
button_mc.label_txt.text = "home";

button_mc.addEventListener(MouseEvent.MOUSE_OVER, hover);
button_mc.addEventListener(MouseEvent.CLICK, clicked);

function hover(e:MouseEvent):void {
	Tweener.addTween(button_mc.bg_mc, {scaleX:1.5, transition:"easeOutElastic", time:1});
	button_mc.removeEventListener(MouseEvent.MOUSE_OVER, hover);
	button_mc.addEventListener(MouseEvent.MOUSE_OUT, out);
}

function out(e:MouseEvent):void {
	Tweener.addTween(button_mc.bg_mc, {scaleX:1, transition:"easeOutElastic", time:1});
	button_mc.removeEventListener(MouseEvent.MOUSE_OUT, out);
	button_mc.addEventListener(MouseEvent.MOUSE_OVER, hover);
}

function clicked(e:MouseEvent):void {
	navigateToURL(new URLRequest("http://www.schoolofflash.com"),"_self");
}

The first three lines of our code import the necessary ActionScript classes. Note that I have decided to use the Tweener class for our animations instead of the traditional Tween class. The Tweener class is much easier to use, not to mention much less buggy. Click here to learn more about the free Tweener class. Line 1 of our code imports the Tweener class, as well as other classes in the caurina.transitions package.

In line 5, we set the buttonMode property to "true". When we do this, we make our Movie Clip behave more like a Button symbol in that it causes the mouse cursor to turn into a hand cursor whenever you hover over the button. Line 6 sets the label text of the button to read "home".

The next two lines create our hover and click events, which trigger the "hover" and "clicked" functions, respectively.

Inside the "hover" function, we want to animate the width of the button background to get that elastic, bouncy animation. We do this using the Tweener.addTween() method. This method takes two main parameters: the instance name of the object being animated and an object containing information on the animation itself. In this case, we want to animate the background of the button by itself. If we just applied the animation to the button, then the text would animate, too. We don't want that, so we're pointing to the bg_mc Movie Clip within the button_mc Movie Clip.

The second parameter is a little more complicated, because it contains numerous property/value pairs that define our animation. The documentation on the Tweener class describes a number of different properties that you can include here, but for this animation, we just want to look at the property of the Movie Clip that we want to animate, the easing function we want to use, and the duration of the animation itself. For this animation, we just want to animate the width of the background; but instead of using the width property, notice that I referenced the scaleX property, which allows you to modify the width of the object as a percentage of its original width. In this instance, I used 1.5 to scale it up to 100% of its original width. To scale it back to its original width in the out function, simply animate the scaleX property back to a value of 1.

Another property commonly used within the Tweener.addTween() method is the "transition" property. By default, if you choose not to specify a value, the Tweener classes uses a simple ease out. If you don't want any easing at all, you would set the transition to "linear." Again, the Tweener documentation contains a description of all the different transition types--which are much more robust than the easing options available with the traditional Tween class. If you decide to use the Tweener class on a regular basis (which I do), then I highly recommend these handy little cheat sheets, which I keep posted on my desk.

The third property I used in this example is the "time" property, which determines the duration of the animation. This number is in seconds, so our button animation will last 1 second. Note that this does not have to be a whole number. If you want your animation to last half a second, you can enter a value of 0.5.

After creating your new Tween, be sure to remove the event listener for the MOUSE_OVER event and add a listener for the MOUSE_OUT event. Try to stay in the habit of removing unneeded listeners. When you're already hovering over a button, you no longer need the MOUSE_OVER event using up processing power. Just remember to add the event back after you move your mouse away from the button (as seen in the out() function).

By now, you should be able to figure out what's going on inside the out() function. When the user moves the mouse cursor away from the button, we simply play the reverse of the previous animation, returning the button to its original width. Then we remove the MOUSE_OUT event and restore the MOUSE_OVER event.

Flexible ActionScript 3 Buttons

As you can see, breaking away from reliance on the timeline allows you to create much more flexible and dynamic interactions. With only very minor tweaks to the code, you can create a variety of different effects.

Click here to download the project file for this tutorial.

Related Post: ActionScript 3 Tutorial - Tweener Transitions

Motion Tweens in Flash CS3 and CS4

October 12th, 2009 | 5 Comments

Flash CS4 changed the way that motion tweens are handled. In CS3, tweens were very timeline-oriented, but CS4 has made them more object-oriented. This tutorial is a great overview of both the old and new ways of creating Motion Tweens using Flash.

(more...)

ActionScript 3 Tutorial – A Better Preloader

October 9th, 2009 | 11 Comments

Having problems with your preloader? It's to be expected. Preloaders have a history of causing a lot of grief among Flash designers. Even once you get the loader bar working, you'll often find that it takes the preloader itself several seconds before it shows up. Which defeats the purpose of having a preloader in the first place. So you dive in deeper and quickly discover that there are a dozen tweaks that have to be made just to get your preloader to show up quicker.

In today's free ActionScript tutorial, you'll learn a better way to create preloaders--a way that doesn't require a bunch of workarounds to get it functioning properly! Enjoy!

Here's the code from the tutorial:

myLoader.addEventListener(Event.COMPLETE, onComplete);
myLoader.addEventListener(ProgressEvent.PROGRESS, onProgress);

function onProgress(e:ProgressEvent):void
{
	var pct:Number = e.bytesLoaded / e.bytesTotal;
	preloader_mc.bar_mc.scaleX = pct;
}

function onComplete(e:Event):void
{
	preloader_mc.x = -1000;
}

myLoader.load(new URLRequest("berries.swf"));

3D Particle Effect – Flash CS4 Tutorial

December 21st, 2008 | 44 Comments

In today's video tutorial, I'll show you how to create an ActionScript 3D particle effect that causes multiple stars to animate out in all directions in 3D space. Here is the ActionScript for this tutorial:

var container:MovieClip = new MovieClip();
addChild(container);

root.transform.perspectiveProjection.fieldOfView = 120;

addEventListener(Event.ENTER_FRAME, addStar);

function addStar(e:Event):void
{
	var mc:star = new star();
	mc.x = stage.stageWidth / 2;
	mc.y = stage.stageHeight / 2;
	mc.z = 0;
	mc.xVel = Math.random() * 4 - 2;
	mc.yVel = Math.random() * 4 - 2;
	mc.zVel = Math.random() * 4 - 2;
	mc.count = 0;
	container.addChild(mc);
	mc.addEventListener(Event.ENTER_FRAME, animate);
}

function animate(e:Event):void
{
	e.currentTarget.x += e.currentTarget.xVel;
	e.currentTarget.y += e.currentTarget.yVel;
	e.currentTarget.z += e.currentTarget.zVel;
	e.currentTarget.count++;
	if (e.currentTarget.count &gt;= 100)
	{
		e.currentTarget.removeEventListener(Event.ENTER_FRAME, animate);
		container.removeChild(MovieClip(e.currentTarget));
	}
}

The Bone Tool – Flash CS4 Tutorial

December 9th, 2008 | 5 Comments

Inverse Kinematics! The feature we've all been waiting for! IK is going to make character animation a lot easier than it once was. With IK, you can build a bone structure to link different pieces of a character or object together in order to make it easier to animate.

In today's video, Craig will discuss how to create and animate bone structures using Flash's Bone Tool.

Custom Motion Paths – Flash CS4 Tutorial

December 2nd, 2008 | 10 Comments

If you're familiar with using motion paths in Flash CS3, then you might be a little confused when trying to create your own custom path using Flash CS4. In Flash CS4, a motion path is automatically created any time you create a motion tween, and there is only so much you can do to customize the path that is created for you.

What if you want to create a motion path from scratch in Flash CS4? Well, in this video, I'll show you exactly how to do it, and you'll discover that it has become easier than ever!