Unlimited Plugins, WordPress themes, videos & courses! Unlimited asset downloads! From $16.50/m
  1. Code
  2. Animation

Creating ActionScripted Animation and Interaction

Read Time:18 minsLanguages:

ActionScript can be a great tool for enhancing your animations. In this tutorial we'll look at the basics of ActionScripted animation. We'll take a look at how to actually move a movie clip using ActionScript, various forms of collision detection and how to use these techniques to add some interaction to your Flash movies. Let's get started!

Step 1 - Setting Up Our File

Let's begin by creating a new Flash movie (ActionScript 3.0). Use the properties panel to set the dimensions to 600px X 350px, at a framerate of 30fps. We'll be writing our code in the main timeline to keep things simple. If you already know how to organize your code in classes, it shouldn't be hard to apply that knowledge to this tutorial.

setting the propertiessetting the propertiessetting the properties

Step 2 - Drawing Our Background

Before we start writing our ActionScript we need a few graphics to work with. We'll keep them pretty basic since we're mostly interested in the ActionScript today.

Start by renaming our layer; double-click on the layername and rename it to "background".

renaming layerrenaming layerrenaming layer

We're going to use the rectangle tool (r) to draw a rectangle. Don't worry about the size or color yet.

Step 3 - Resizing Our Background

Double-click on your rectangle to select the fill and border. Open the properties pane so you can adjust the dimensions of your rectangle.

Change the width and height to the same values as the width and height of your stage and make sure the x and y position are set to 0. Now our rectangle perfectly matches our stage.

Step 4 - Adjusting Our Background Color

Select the fill color of the rectangle by clicking it once. We're going to make it look a bit more interesting by adding a gradient to it.

With the rectangle selected, open the color panel and change the fill color from "solid" to "radial". The rectangle's fill has now been changed to a radial gradient. You can alter the colors of the gradient by clicking on the small swatches in the gradient bar in the color panel. Double-click on the left swatch to change it to a blue color. Do the same for the right swatch to change it to a similar, but darker blue.

applying a gradientapplying a gradientapplying a gradient

To make the gradient a little more subtle we'll tweak the gradient slightly using the gradient transform tool. Select the gradient transform tool (f) and click on the gradient to select it.

The gradient transform tool shows several handles. One in the middle for moving the entire gradient, and three on the edge. One for rotating the gradient, one for scaling the gradient and one for compressing the gradient.

First rotate the gradient so that its axis is vertical. Then compress the gradient into an oval so that it better matches the shape of our rectangle.

gradient transform tool 01gradient transform tool 01gradient transform tool 01

To finish it off, scale the gradient up until only the corners of our rectangle look darker than the center (this step is easier if you zoom out from the stage a bit). You should end up with something similar to the image below:

final backgroundfinal backgroundfinal background

Step 5 - The Ball

The next graphic we need is the Movie Clip we're going to animate. We'll use a circle.

Create a new layer for the Movie Clip and draw a circle. Select the circle and hit F8 to bring up the "convert to symbol" menu.

Name the Movie Clip "ball_mc", make sure the registration point is set to the center and the checkbox for "Export for ActionScript" is marked.

convert to symbolconvert to symbolconvert to symbol

When you click ok, Flash will give you the warning seen below. This is no problem. Flash is looking for a custom class named "ball_mc". But since we haven't written any such class, Flash can't find it and warns us it will automatically generate one when we export our file. This is fine, we only marked the "Export for ActionScript" checkbox so we can dynamically place our Movie Clip using ActionScript.


Delete the Movie Clip from the stage, we'll be placing it using ActionScript later on.

Step 6 - Placing a Movie Clip using ActionScript

Finally, time to start writing some code! We'll be working towards our final result in a number of steps in order to explain some basic concepts. We'll keep going back to add a few lines until we reach the final result.

Let's start by looking at how to use ActionScript to take a Movie Clip out of our library and place it on the stage.

If you look at the code below, you'll notice three seperate steps. We create a variable named "ball" to hold a reference to the newly created instance of our Movie Clip. Next we use the "addChild" method to add our ball to the displaylist. If you were to forget the last step, you would create an instance of the ball_mc Movie Clip, but you wouldn't be able to see it.

If we export the Flash movie now, we'll see that the ball has been placed in the top left corner of the Flash movie. We haven't specified a position so it's placed at the default x,y position of 0, 0.

Step 7 - Movie Clip Properties

The top left corner of the screen is a pretty silly position for our ball, we can only see a quarter of the Movie Clip! Luckily for us, a Movie Clip has a number of properties we can change.

The properties we want to change right now are the x and y position of the Movie Clip. Check out the code sample below to see how we can control the positioning of our Movie Clip:

(Additional lines: 5,6)

If you export your movie now, you'll see that the Movie Clip is no longer in the top left corner of the screen but at the x,y coordinates we specified. Movie Clips have many other interesting properties that you can set. You can check the help files for a list of these properties.

By changing the Movie Clip's x and y properties repeatedly over a period of time, we can make it move! Let's take a look at how to do that.

Step 8 - Moving Our Movie Clip

In order to move our MovieClip we'll set up an "eventListener" which executes a function everytime the "ENTER_FRAME" event fires. In our case, approximately 30 times a second.

Everytime the "ENTER_FRAME" event fires, our "eventListener" will execute our mover function that will substract 3 from our MovieClip's x and y properties, thereby causing it to move.

(Additional lines: 8-13)

If you export the movie now you'll see the Movie Clip moves away towards the edge of the Flash movie at a continuous speed. Since we're doing nothing to stop it or change it's direction it'll continue to move in that direction indefinitely. I'd say it's time we added some boundaries.

Step 9 - Finding Our Boundaries

If we want to stop our Movie Clip from moving until it disappears, we'll need to set some boundaries for it. The edges of our Flash movie seem perfect for the job, so let's set up some variables for our boundaries.

We already know the y position of the top of the stage is 0 and the x position of the right of our stage is also 0. The variables for those boundaries are therefore easy to set. We know our stage is 600 pixels wide, but rather than simply setting our right boundary to 600 pixels, we're going to use ActionScript to determine how wide our stage is. We'll set the bottom boundary in the same way by requesting the height of the stage using ActionScript.

(Additional lines: 1-4)

Right now we're using the edges of our stage as boundaries. In your own projects you might set your boundaries differently, you could create a new rectangle movie clip for example and use its x,y position, width and height to calculate your boundaries.

Step 10 - Collision Detection

We've determined what our boundaries are and saved that information in four variables. Mind you, we haven't yet told our mover function what to do with this information.

Since our Movie Clip is perfectly round, we can easily determine when it crosses a boundary. For instance when it's x position (it's center point) plus half its width equals or exceeds the x position of the right boundary, we know it's crossing that boundary and we should turn it around.

In order to do that we're going to store the modifiers to its x and y properties in a set of variables so we can easily change them. We'll also add a set of "if" statements to the mover function to check for boundary collisions.

(Additional lines: 6,7 + 20-36)

If you export the Flash movie now, you'll see that the mover function checks continuously to see if the ball collides with any of the boundaries we've set. If a collision occurs the ball is displaced slightly to make sure it stays within the boundaries we've set and its direction is reversed:

Step 11 - Friction

Even though we've set up some boundaries to make sure the ball doesn't go flying off stage, the ball never stops moving.

If you grab any object from your desk, for instance your computer mouse and give it a nudge, it's going to stop moving pretty quickly after you stop applying force. Friction between your desk and your mouse wears down its velocity until your mouse is stationary again. We can imitate this effect in ActionScript pretty easily.

We'll create a new variable named "friction", and assign it a value slightly smaller than 1, a value of 0.98 works pretty well. Now everytime we run the mover function, we'll multiply our vx and vy variables with our friction variable, decreasing them slightly.

(Additional lines: 8 + 21,22)

If you export the file now, you'll see that friction quickly wears down our ball's velocity until it comes to a stand still. Friction helps to make your animation feel more "real". Super Mario for example doesn't come to a full stop instantly when you let go of the controls. Instead, he slides on for a moment until friction brings him to a stand still.

Friction is just one of the ways you can affect your animation by adding a modifier to the x and y velocity of your object. You could simulate gravity by adding to the y velocity or wind by adding or subtracting to or from the x and y velocity depending on your desired wind direction.

Step 12 - The Arrow

Now that we've seen how to place and move a Movie Clip using ActionScript it's time for some interaction.

Draw an arrow using a combination of the rectangle, transform and line tools:

create an arrowcreate an arrowcreate an arrow

Step 13 - Setting Up the Arrow Movie Clip

We're going to turn the arrow into a Movie Clip with slightly different settings than our ball Movie Clip.

Select the arrow, hit F8 to bring up the "convert to symbol" window and name the arrow Movie Clip "arrow_mc". Make sure the "Export for ActionScript" checkbox is marked as before, but this time set the registration point to the center left position as in the screenshot.

A Movie Clip rotates around its registration point and we want to make sure our arrow rotates around its tip.

arrow Movie Cliparrow Movie Cliparrow Movie Clip

Delete the arrow Movie Clip from the stage, we'll be placing it with ActionScript, just like the ball.

Step 14 - Placing and Moving the Arrow

We'll place the arrow on the stage in the same manner as our ball Movie Clip. We'll name it pointer.

Since we just want to make sure our pointer is always at the same position as our mouse cursor we'll only need two lines of code. Every time our mover function executes we'll update the x,y position of our pointer to the x,y position of our mouse cursor.

(Additional lines: 11-15 + 21,22)

Step 15 - Hiding the Mouse Cursor

Let's hide our regular mouse cursor so that we can only see our pointer movieclip while interacting with our Flash movie.

(Additional line: 15)

Step 16 - Finding the Angle Between the Pointer and the Ball

We now have a pointer which follows the mouse around, let's make sure it actually points at our ball. In order to do this we'll need to find the angle between the pointer and the ball.

We can use trigonometry to calculate our required angle, but first we'll need to find the distance between the pointer and the ball along the x and y axis. Easy enough considering we know both their positions. Let's look at how to calculate it first, then we'll add it into our code.

Now that we have the required distances, we can calculate the angle in radians. Radians is the standard unit of angular measurment in Mathematics. A perfect circle is 360 degrees or PI * 2 radians.

While Radians are the standard unit of measurement for angles in Math, if we want to set our movie clip's rotational property, we'll need to convert the angle to degrees instead.

Step 17 - Converting Radians to Degrees

Converting radians to degrees or vice versa is pretty simple. In ActionScript it would look like this:

Degrees = Radians * 180 / Math.PI;

Radians = Degrees * Math.PI / 180;

Step 18 - Putting it All Together

Since we'll need to rotate the pointer everytime either the ball or the mouse moves, we'll place the rotation code in our mover function.

(Additional lines: 27-29 + 34-38)

Step 19 - Poking the Ball

Ok, so we got our ball moving, we got our pointer moving, we even got our pointer to actually point at the ball. I think it's time we made something happen when we touch the ball.

We've already taken a look at distance-based collision detection. When the distance between our ball's centerpoint and a boundary is less than half the width of our ball, we know a collision is occurring. This works quite well for perfect circles, since the distance between their centerpoint and their circumference never changes. This doesn't, however, work so well for irregular shapes.

Let's take a look at a different method of collision detection, this time we'll use the hitTest method. HitTest is a standard ActionScript function that comes in two flavours. The first, "hitTestObject" checks if two objects are colliding by checking if their boundingboxes (those thin blue rectangles you see around Movie Clips when you select them) are overlapping.

This method works perfectly for rectangular MovieClips, but since the bounding box is always rectangular, it's not very accurate for irregular shapes or ovals.

The second method checks a point (x,y) position against a shape. Much more accurate for irregular shapes, even though there's no easy way to check one irregular shape against another. It's perfect for us though, we have one none rectangular shape (our ball) and one point (the tip of our arrow) that we want to check against each other. So we run the "hitTestPoint()" method in our mover function while supplying our ball Movie Clip and the x,y position of our arrow as input. The method will return a boolean (true or false) value depending on whether or not a collision is occurring.

(Additional lines: 45-47)

If we run our Flash movie now, we'll see that as soon as the tip of the arrow touches the ball, the Flash movie starts tracing out "poke" into the output panel.

Step 20 - Moving the Ball With the Pointer

We already know the angle between the ball and the pointer and we already know when the pointer is poking the ball. It's therefore a pretty small step from here to actually push the ball directly away from the pointer.

Remember those vx and vy variables we use to set the velocity for our ball? Using sine and cosine we can change those two variables to a value that causes the ball to fly away from the pointer in the direction you poke. We take the cosine of the angle and multiply it with a number to set the velocity along the x axis, we do the same with the sine of the angle to set a velocity along the y-axis. The greater the number you use to multiply the cosine or sine result, the faster the ball will go.

(Additional lines: 47,48)


These are just the basics of ActionScripted animation but I hope they've given you some ideas on how to apply this knowledge in your own projects. By expanding on these techniques you can create many interesting and useful effects for your Flash projects. Thanks for reading!

Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.