# Creating ActionScripted Animation and Interaction

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.

## 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".

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.

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.

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:

## 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.

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.

var ball:MovieClip;
ball = new ball_mc();


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:

var ball:MovieClip;
ball = new ball_mc();

ball.x=325;
ball.y=150;



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.

var ball:MovieClip;
ball = new ball_mc();

ball.x=325;
ball.y=150;

function mover(e:Event):void {
ball.x -= 3;
ball.y -= 3;
}



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.

var top:Number=0;
var right:Number=stage.stageWidth;
var bottom:Number=stage.stageHeight;
var left:Number=0;

var ball:MovieClip;
ball = new ball_mc();

ball.x=325;
ball.y=150;

function mover(e:Event):void {
ball.x -= 3;
ball.y-= 3;
}


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.

var top:Number=0;
var right:Number=stage.stageWidth;
var bottom:Number=stage.stageHeight;
var left:Number=0;

var vx:Number=3;
var vy:Number=3;

var ball:MovieClip;
ball = new ball_mc();

ball.x=325;
ball.y=150;

function mover(e:Event):void {

ball.x-=vx;
ball.y-=vy;

if (ball.x<left+ball.width/2) {
ball.x=left+ball.width/2;
vx*=-1;
} else if (ball.x > right - ball.width / 2) {
ball.x=right-ball.width/2;
vx*=-1;
}
if (ball.y<top+ball.height/2) {
ball.y=top+ball.height/2;
vy*=-1;
} else if (ball.y > bottom - ball.height / 2) {
ball.y=bottom-ball.height/2;
vy*=-1;
}

}


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.

var top:Number=0;
var right:Number=stage.stageWidth;
var bottom:Number=stage.stageHeight;
var left:Number=0;

var vx:Number=3;
var vy:Number=3;
var friction:Number=0.98;

var ball:MovieClip;
ball = new ball_mc();

ball.x=325;
ball.y=150;

function mover(e:Event):void {

vx*=friction;
vy*=friction;

ball.x-=vx;
ball.y-=vy;

if (ball.x<left+ball.width/2) {
ball.x=left+ball.width/2;
vx*=-1;
} else if (ball.x > right - ball.width / 2) {
ball.x=right-ball.width/2;
vx*=-1;
}
if (ball.y<top+ball.height/2) {
ball.y=top+ball.height/2;
vy*=-1;
} else if (ball.y > bottom - ball.height / 2) {
ball.y=bottom-ball.height/2;
vy*=-1;
}
}


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:

## 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.

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.

var friction:Number=0.98;

var ball:MovieClip;
ball = new ball_mc();

ball.x=325;
ball.y=150;

var pointer:MovieClip = new arrow_mc();
pointer.x = mouseX;
pointer.y = mouseY;
Mouse.hide();

function mover(e:Event):void {

pointer.x = mouseX;
pointer.y = mouseY;

vx*=friction;
vy*=friction;

ball.x-=vx;
ball.y-=vy;

if (ball.x<left+ball.width/2) {
ball.x=left+ball.width/2;
vx*=-1;
} else if (ball.x > right - ball.width / 2) {
ball.x=right-ball.width/2;
vx*=-1;
}
if (ball.y<top+ball.height/2) {
ball.y=top+ball.height/2;
vy*=-1;
} else if (ball.y > bottom - ball.height / 2) {
ball.y=bottom-ball.height/2;
vy*=-1;
}
}


## 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.

var friction:Number=0.98;

var ball:MovieClip;
ball = new ball_mc();

ball.x=325;
ball.y=150;

var pointer:MovieClip = new arrow_mc();
pointer.x = mouseX;
pointer.y = mouseY;
Mouse.hide();

function mover(e:Event):void {
pointer.x = mouseX;
pointer.y = mouseY;

vx*=friction;
vy*=friction;

ball.x-=vx;
ball.y-=vy;

if (ball.x<left+ball.width/2) {
ball.x=left+ball.width/2;
vx*=-1;
} else if (ball.x > right - ball.width / 2) {
ball.x=right-ball.width/2;
vx*=-1;
}
if (ball.y<top+ball.height/2) {
ball.y=top+ball.height/2;
vy*=-1;
} else if (ball.y > bottom - ball.height / 2) {
ball.y=bottom-ball.height/2;
vy*=-1;
}
}


## 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.

	dx = mouseX - ball.x;
dy = mouseY - ball.y;


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.

	dx = mouseX - ball.x;
dy = mouseY - ball.y;
ar = Math.atan2(dy,dx);


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.

var top:Number=0;
var right:Number=stage.stageWidth;
var bottom:Number=stage.stageHeight;
var left:Number=0;

var vx:Number=3;
var vy:Number=3;
var friction:Number=0.98;

var ball:MovieClip;
ball = new ball_mc();

ball.x=325;
ball.y=150;

var pointer:MovieClip = new arrow_mc();
pointer.x = mouseX;
pointer.y = mouseY;
Mouse.hide();

function mover(e:Event):void {

var dx:Number;
var dy:Number;
var ar:Number

pointer.x = mouseX;
pointer.y = mouseY;

dx = mouseX - ball.x;
dy = mouseY - ball.y;
ar = Math.atan2(dy,dx);
var a:Number = ar * 180 / Math.PI;
pointer.rotation = a;

vx*=friction;
vy*=friction;

ball.x-=vx;
ball.y-=vy;

if (ball.x<left+ball.width/2) {
ball.x=left+ball.width/2;
vx*=-1;
} else if (ball.x > right - ball.width / 2) {
ball.x=right-ball.width/2;
vx*=-1;
}
if (ball.y<top+ball.height/2) {
ball.y=top+ball.height/2;
vy*=-1;
} else if (ball.y > bottom - ball.height / 2) {
ball.y=bottom-ball.height/2;
vy*=-1;
}
}


## 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.

var top:Number=0;
var right:Number=stage.stageWidth;
var bottom:Number=stage.stageHeight;
var left:Number=0;

var vx:Number=3;
var vy:Number=3;
var friction:Number=0.98;

var ball:MovieClip;
ball = new ball_mc();

ball.x=325;
ball.y=150;

var pointer:MovieClip = new arrow_mc();
pointer.x = mouseX;
pointer.y = mouseY;
Mouse.hide();

function mover(e:Event):void {
var dx:Number;
var dy:Number;
var ar:Number

pointer.x = mouseX;
pointer.y = mouseY;

dx = mouseX - ball.x;
dy = mouseY - ball.y;
ar = Math.atan2(dy,dx);
var a:Number = ar * 180 / Math.PI;
pointer.rotation = a;

vx*=friction;
vy*=friction;

ball.x-=vx;
ball.y-=vy;

if(ball.hitTestPoint(pointer.x, pointer.y,true)){
trace('poke');
}

if (ball.x<left+ball.width/2) {
ball.x=left+ball.width/2;
vx*=-1;
} else if (ball.x > right - ball.width / 2) {
ball.x=right-ball.width/2;
vx*=-1;
}
if (ball.y<top+ball.height/2) {
ball.y=top+ball.height/2;
vy*=-1;
} else if (ball.y > bottom - ball.height / 2) {
ball.y=bottom-ball.height/2;
vy*=-1;
}
}


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.

var top:Number=0;
var right:Number=stage.stageWidth;
var bottom:Number=stage.stageHeight;
var left:Number=0;

var vx:Number=3;
var vy:Number=3;
var friction:Number=0.98;

var ball:MovieClip;
ball = new ball_mc();

ball.x=325;
ball.y=150;

var pointer:MovieClip = new arrow_mc();
pointer.x = mouseX;
pointer.y = mouseY;
Mouse.hide();

function mover(e:Event):void {
var dx:Number;
var dy:Number;
var ar:Number

pointer.x = mouseX;
pointer.y = mouseY;

dx = mouseX - ball.x;
dy = mouseY - ball.y;
ar = Math.atan2(dy,dx);
var a:Number = ar * 180 / Math.PI;
pointer.rotation = a;

vx*=friction;
vy*=friction;

ball.x-=vx;
ball.y-=vy;

if(ball.hitTestPoint(pointer.x, pointer.y,true)){

vx=Math.cos(ar)*10;
vy=Math.sin(ar)*10;

}

if (ball.x<left+ball.width/2) {
ball.x=left+ball.width/2;
vx*=-1;
} else if (ball.x > right - ball.width / 2) {
ball.x=right-ball.width/2;
vx*=-1;
}
if (ball.y<top+ball.height/2) {
ball.y=top+ball.height/2;
vy*=-1;
} else if (ball.y > bottom - ball.height / 2) {
ball.y=bottom-ball.height/2;
vy*=-1;
}
}


## Conclusion

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!

• Zsbee

Very well commented tutorial! Nice tutorial! You can learn a lot in it!

• http://www.kreativeking.com Clemente G

Nice, I take it you read Keith Peters Book, “Making Things Move”. If anyone is interested in learning more about this. Check out http://astore.amazon.com/bit101-20/detail/1590597915

• ice

I LOVE that book. I retaught myself trigonometry in anticipation for that book; made everything so much better.

• Midnyt

Semi-offtopic…

I never got around to learning Trig in school, any advice (books, websites, etc)?

Thanks

• http://www.neilrpearce.co.uk Neil pearce

Me to, great book and very nice tutorial!

• http://labs.dariux.com Dario Gutierrez

• snottlebocket

Keith Peters is one of the best ActionScript writers around, I haven’t read this book but I read the original for ActionScript 2.0 years ago. I think he wrote a new bppl on more advanced techniques to recently, should be very interesting.

• http://labs.dariux.com Dario Gutierrez

Great tut, a good reference for me.

• http://dtxcreative.com Zack

thanks, going to do this one tonight. looks really useful.

• Andre

for the people who already have some knowlege how to use correctly the actionscript 3.0

Congratulations for this tutorial.

• NETWORK

Join the TUTS+ NETWORK Facebook Fan Page!
Get updated on the latest tutorials from all of TUTS+ Programs.

A great way to be updated!

• http://www.dsaportfolio.com.br/ Diego SA

That’s cool and fun tutorial.

• cyb

fun fun fun

• http://frankyaguilar.com Franky

Fun. This is a great start to an air hockey game!

• Odisoes

Easy, clean and functional, like good design. I think that your book will be interesant.

• Odisoes

I mean, simple, clean and functional. Easy is not simple.

• Ibo Bonduelle

Very nice tutorial. I love it. I’m very new to ActionScript. I can use Flash with the timeline, create motion tweens and so on. But I never used ActionScript before. Therefor I just copypasted your code and tried to understand what happens when.

It worked. Some values weren’t correct though, but I fixed it and now it works. Thanks a lot!

• http://tuts.cgbaran.com CgBaran Tuts

Cool tutorial i will try that!! thanks

• Janet

Really helpful. Can see lots of applications. Brilliant thanks.

• akash

pls help me
on flash work

• Bisbis

Great tut!
this blog is turning into something big

• http://blog.circlecube.com Evan Mullins

Nice work. Very simple to follow from start to finish.

• http://www.emagenstudios.com Jesse Esquibel

This is a really great tut. I followed every step and it is working but I can’t get the arrow to point at the circle. I’ll need to mess around with the values and the angles.

• http://blog.flashandcoffee.com Vjekoslav Ratkajec

First time I see that someone is having ball_mc as class name. Strange naming convention. And great tutorial.

• http://http://www.crearedesign.co.uk/ rory

That is awesome, just did the tutorial and it works!!
Pretty straight forward to, cheers guys…I’m going to replace to arrow and ball with different images now see what fun I can create.

• http://qmmr.org Marcin

Thanks for this tutorial!

• akash

hii
i am akash
nice work no fantastic work
pls help me bcz i m very poor person but my interest iis going toflash work
but here is not teacher

vere well explained,thank, this is what call scripting with science, peace

• mahi

Very nice……

• Mst

Great tutorial! Thanks!

• clifton

need help
how do i put script and file together
also how do i put arrow and ball back in project

• flora

really nice sine and cos ;)

• NicoB

Looks a lot like LearnFlash: Introduction to Actionscript – nice reminder though

• Ananth

Excellent. Gives a good understanding of basic Action Script application.

• Alexander Rose

Very clearly explained, as a newbee to AS3 this provides some insightful advice. Thank you for taking the time to write this.

• chawki

Really amazing. That’s very cool. I have to understand the actionscript first then installing flash cs4 because I work with adobe flash cs3. Good work.

• http://www.tovtoda.co.il/Tenders.aspx?si=28&ca=140 בניית פרגולות

Thank you for a well understood and clear explanation of ActionScripted animation basics, it helped figuer a lot of issues i was stuck in.

• http://www.steel-art.co.il/ דלתות כניסה

ActionScript is an excellent tool, it helped me a lot with enhancing my animations, your tutorial is well written, keep up with your good work! Thank you.

• http://www.24shaot.com/colors/ צבעי

helped me a lot with improving my animations.
thank you Very nice Amazing script