Timer Class

  • November 2019
  • PDF

This document was uploaded by user and they confirmed that they have the permission to share it. If you are author or own the copyright of this book, please report to us by using this DMCA report form. Report DMCA


Overview

Download & View Timer Class as PDF for free.

More details

  • Words: 13,271
  • Pages: 82
Timer Class Actionscript 3 timers are used to run pieces of code or animation on a specific time sequence. They come in real handy when you want something to  be done repeatedly, but not in every frame. This tutorial teaches you the basics of actionscript timers and how to use them in your flash movies. We'll  be creating a small movie (the one you see above), so you'll learn everything in practice. So start your Flash and let's get going.

Setting up the environment 1. Create a new Flash Actionscript 3.0 document of size 400x400.  2. Create a dynamic text field of size 100x60. You can draw it anywhere on the stage.  3. Embed the numerals of the text field. We need to do this, because we'll be animating the numbers later on. Give the text field an instance name of  "myNumberTextBox". 

4. Convert the text field into a movie clip. Name it myNumberMC. Set the registration point in the center.  5. Linkage the movie clip to a class called "NumberMovieClip".  6. Remove the movie clip from the stage. 

Moving into Actionscript 3.0  Now it's time for the timer. Create a layer for actionscript and type the following. 

//We need these for the animation import fl.transitions.*; import fl.transitions.easing.*; /* Create a timer that is called once every second (1000 milliseconds). This timer will be called infinitely, because the second parameter is zero. */ var timer:Timer = new Timer(1000,0); timer.addEventListener (TimerEvent.TIMER, changeNumber);

timer.start (); //Create the smaller number seen on the stage var myNumber:NumberMovieClip = new NumberMovieClip(); //Position the number in the center of the stage myNumber.x = stage.stageWidth / 2; myNumber.y = stage.stageHeight / 2; //Add it to the stage addChild (myNumber); //Make it invisible at the beginning myNumber.visible = false; //Create the larger number seen on the stage var myNumberBig:NumberMovieClip = new NumberMovieClip(); //Position the number in the center of the stage myNumberBig.x = stage.stageWidth / 2; myNumberBig.y = stage.stageHeight / 2; //Make it a lot bigger (you can change these to whatever you want) myNumberBig.scaleY = 20; myNumberBig.scaleX = 20; //Reduce the alpha myNumberBig.alpha = 0.1; //Add it to the stage addChild (myNumberBig); //Make it invisible at the beginning myNumberBig.visible = false; /* Our timer calls this function. The timer delay defines how frequently this function is called. */ function changeNumber (e:Event):void { /* Make our numbers visible. */ myNumber.visible = true; myNumberBig.visible = true;

1);

//Assign a new numerical value for the movie clip myNumber.myNumberTextBox.text = String(e.target.currentCount -

/* Animate the smaller number using the TransitionManager. The animation lasts exactly as long as our timer delay is. */ TransitionManager.start (myNumber, {type:Fade, direction:Transition.IN,

duration:(timer.delay * 0.001), easing:Regular.easeIn}); //Assign a new numerical value for the movie clip myNumberBig.myNumberTextBox.text = String(e.target.currentCount - 1); /* Animate the larger number using the TransitionManager. The animation lasts exactly as long as our timer delay is. */ TransitionManager.start (myNumberBig, {type:Zoom, direction:Transition.IN, duration:(timer.delay * 0.001), easing:Regular.easeIn}); } Test your movie, and you should have a similar movie as mine. There is one other timer event available for you to use. It's called the "timerComplete".  As the name suggests, it is called when the timer finishes. In this tutorial, that would be never, since our timer will run infinitely. That's the end of this  tutorial. If you have any question concerning the timer, please post them in the forum.

Actionscript 3.0 Preloader In this tutorial, I'm going to show you how to build a preloader. You should have your own preloader in minutes! Follow these steps.

1. Create a new document. 2. Name the first layer to "loader bar" 3. Draw a line. This line will be our preloader bar.  4. Convert the line into a movie clip. Set the registration point to the top left corner.  5. Give the line an instance name of "preloaderBar". 6. Create a new layer called "actions"  7. Type the following in the "actions" layer 

preloaderBar.scaleX = 0; var loader = new Loader(); loader.load(new URLRequest("main.swf")); loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onCompleteHandler); loader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, progressHandler); addChild(loader); Explanation: First we set our preloader's X scale to zero. This way, the user can't see the preloader at the beginning of the loading process. Then, we  create a Loader object. The Loader object is used to load SWF files or image files. After the Loader is created, we tell it load our main movie  (main.swf). Then comes the important part, we assign event handlers for the loader. To be more specific, we are using the "contentLoaderInfo" to  access loading progress information and statistics. In this case, we want to know when the loading is still in progress (progressHandler) and when the  loading is complete (onCompleteHandler). Last, we add the loader to the stage.

NOTE: You must have the "main.swf" file in the same directory as this loader file! 8. Now that we have our loader ready, we can write the functions that are responsible for animating the preloader. Type the following

function onCompleteHandler(e:Event):void { preloaderBar.visible = false; } function progressHandler(e:ProgressEvent):void { var per = e.bytesLoaded/e.bytesTotal; preloaderBar.scaleX = per; loader.visible = true; } Explanation: The "onCompleteHandler" is called when the loading is done. In this case, we don't want to show the user our preloader anymore, so we  make it invisible. The "progressHandler" is called everytime the loading progresses. Here, we simply calculate the percentage that has been loaded  (loaded/total size). Then, we assign into the preloader's X scale property the precentage value. So when the percentage is 1 (loading is done), the  "preloaderBar" will be at full width (scaleX = 1). 9. Test your movie!

Actionscript 3 External Classes

This tutorial is all about external Actionscript 3 classes. I will teach you how to linkage movie clips to an actionscript class and then we'll create an  external class. The end product in seen above. The movie uses one external class and only a few lines of code is written in the main timeline. So why  do we use external classes? To put it simple, external classes help you to stay more organized. External classes are part of a programming paradigm  called "object oriented programming". The subject is very broad, so I will not go into that. In this tutorial, you don't need a great knowledge of OOP  anyways. SO start your Flash IDE and let's get started!

Setting up the environment 1. Create a new document of size 300x300.  2. Draw a star on the stage. The polystar will help you in that.  3. Convert the star into a movie clip. Give it a name "Star" and set the registration point to the center.  4. Linkage the movie clip to a class named "Star" (right click the movie clip in the library and select "Linkage"). 

Don't worry about the Actionscript Class Warning. It warns you, because Flash can't find a class named "Star". That's normal since we haven't created  that class yet!  5. Remove the star from the stage. 

Moving into Actionscript 3  6. Create a new Actionscript file. 

7. Type the following in the class 

package { import flash.display.MovieClip; import flash.geom.ColorTransform; import flash.events.*; /* This class represents the Star movie clip we drew on the stage. We extend this class to a movie clip, thus allowing us to use movie

clip's functions and properties. */ public class Star extends MovieClip { private var starColor:uint; private var starRotation:Number; /* This is called the constructer of the class. It is called every time we create a new Star instance. In the constructor, we assign a random color to the star

and set some

of it's properties. */ public function Star () {

//Calculate a random color this.starColor = Math.random() * 0xffffff; associated with star.

// Get access to the ColorTransform instance

var colorInfo:ColorTransform = this.transform.colorTransform; // Set the color of the ColorTransform object. colorInfo.color = this.starColor; // apply the color to the star this.transform.colorTransform = colorInfo; //Assign a random alpha for the star this.alpha = Math.random(); //Assign a random rotation speed this.starRotation = Math.random() * 10 - 5; //Assign a random scale this.scaleX = Math.random(); this.scaleY = this.scaleX;

}

//Add ENTER_FRAME where we do the animation addEventListener(Event.ENTER_FRAME, rotateStar);

//This function is responsible for the rotation of the star

}

private function rotateStar(e:Event):void { this.rotation += this.starRotation; } }

8. Save the file as "Star" in the same directory where your main movie is (this is very important!). The movie won't work without the correct file name  and location. File names must always be the same as the class name.  9. You can close the actionscript class now. Go to your main movie and type the following code in the first frame. 

/* Create 100 stars on the stage. Assign a random position to each. All the star animation etc. are done in the "Star" class. */ for (var i = 0; i < 100; i++) { var star:Star = new Star(); star.x = stage.stageWidth * Math.random(); star.y = stage.stageHeight * Math.random(); addChild (star); } 10. You are done, test your movie! I hope you enjoyed 

Actionscript 3.0 Events In order to create an interactive Flash application, we need to learn something about events. An event is something that just happens in the  application. There are many different types of events, such as mouse clicks, mouse move and mouse out. In this tutorial, you’ll learn how to respond to  such events.  Note: You should already be familiar with the  basics of actionscript 

Handling mouse clicks To create a movie clip that responds to mouse clicks, follow these steps. 1. Draw a rectangle and convert it into a movie clip (press F8). 2. Give the rectangle an instance name of ”myRectangle”. 3. Create a new layer called ”actions”. 4. Type the following code in the actions panel (press F9 if you can’t see the panel)

function rectangleClicked(evt:Event):void { myRectangle.alpha = 0.2; } Explanation: The function parameter is an event type. We call it ”evt” in our function. We’ll cover the Event type a little later. For now, just remember  that you need to give an event handler an event parameter. Once the user clicks the button, the rectangle’s alpha is going to change.

5. So how do we know when the rectangle is clicked? For this , we use the ”addEventListener” method. Type the following.

myRectangle.addEventListener(MouseEvent.CLICK, rectangleClicked); Explanation: The ”addEventListener” adds a listener to the rectangle. The first parameter describes which event we are listening. We use  ”MouseEvent.CLICK”, because we want to know when the user clicks the rectangle. The second parameter defines which function we call, when the  user clicks the rectangle. 

6. Test your movie!  

< h3>Handling mouse hovers  If you want the object to respond on a mouse hover, you only need to change some parts of the code. Here is the code for mouse hover.

function rectangleOver(evt:Event):void { myRectangle.alpha = 0.5; } myRectangle.addEventListener(MouseEvent.MOUSE_OVER, rectangleOver); Explanation: This time we want to listen for a "MOUSE_OVER" event. We added another event listener to the rectangle for this. 

Handling mouse out If you want the object to react when you move your mouse out of the rectangle, you apply the following code (don't delete the old functions). 

function rectangleOut(evt:Event):void { myRectangle.alpha = 1; } myRectangle.addEventListener(MouseEvent.MOUSE_OUT, rectangleOut); Now we have an interactive rectangle! You could use this in your website for example as a button. Remember, you can change the shape of the  rectangle anyway you want to give it a nice look.

Final code: 

function rectangleClicked(evt:Event):void { myRectangle.alpha = 0.2; } myRectangle.addEventListener(MouseEvent.CLICK, rectangleClicked); function rectangleOver(evt:Event):void { myRectangle.alpha = 0.5; } myRectangle.addEventListener(MouseEvent.MOUSE_OVER, rectangleOver); function rectangleOut(evt:Event):void { myRectangle.alpha = 1; } myRectangle.addEventListener(MouseEvent.MOUSE_OUT, rectangleOut);

The Event type  You already know that when defining a function that responds to an event, you need an Event parameter for that function. Let me give you an example  about this mysterious "Event" parameter. Type the following in the actions panel (we are still using the same rectangle "myRectangle").

myRectangle.addEventListener(MouseEvent.CLICK, clickHandler); function clickHandler(event:Event):void { trace("Type of event: " + event.type); trace("The event occured on: " + event.target.name); } Now test your movie. You should see the following when you click the rectangle.

As we can see, the event parameter tells us something about the occured event. Most importantly, it tells us what object caused the event. This comes  very handy later on, when we use the same event handler for multiple objects. With the event parameter, we know which object caused the event.

Actionscript 3 Filters

In this tutorial, we're going to apply blur and bevel filters to images. All the animation is done with Actionscript 3.0 of course. Move your mouse over to  the images to see the effects. When you master these, you'll be able to create other filter effects as well. So start your Flash and let's get started. 

Setting up the environment  1. Create a new document of size 500x250.  2. Import two images to the stage (about size 200x200). You can import one rectangular and one round image as I have done.  3. Convert both images into movie clips. You can name them to whatever you want. Set the registration points to the center.  4. Give them instance names of "apple01" and "apple02". 

Moving into Actionscript 3  Open your actions panel and type the following. 

//These are used for animating the filters var blurSpeed:Number = 1; var bevelSpeed:Number = 5;

//Add the MOUSE_OVER listener to each apple apple01.addEventListener (MouseEvent.MOUSE_OVER, mouseOverApple01); apple02.addEventListener (MouseEvent.MOUSE_OVER, mouseOverApple02); //Add the MOUSE_OUT listener to each apple apple01.addEventListener (MouseEvent.MOUSE_OUT, mouseOutApple01); apple02.addEventListener (MouseEvent.MOUSE_OUT, mouseOutApple02); /* Add the ENTER_FRAMEs for both apples, so we can animate them in each frame. */ apple01.addEventListener (Event.ENTER_FRAME, enterFrameApple01); apple02.addEventListener (Event.ENTER_FRAME, enterFrameApple02); // Create and assign the blur filter to apple01. var blur:BlurFilter = new BlurFilter(); blur.blurX = 20; blur.blurY = 20; blur.quality = BitmapFilterQuality.HIGH; apple01.filters = [blur]; //Create a BevelFilter for apple02 var bevelFilter:BevelFilter = new BevelFilter(10, 45, 0x000000, 1, 0xffffff, 1, 0, 0, 0, BitmapFilterQuality.HIGH, BitmapFilterType.INNER, false); apple02.filters = [bevelFilter]; //Set the default values (mouse is not over the apples) var mouseIsOverApple01:Boolean = false; var mouseIsOverApple02:Boolean = false; //This is called when mouse is over apple01 function mouseOverApple01 (event:MouseEvent):void { mouseIsOverApple01 = true; } //This is called when mouse is over apple02 function mouseOverApple02 (event:MouseEvent):void { mouseIsOverApple02 = true; } //This is called when mouse is out of apple01 function mouseOutApple01 (event:MouseEvent):void { mouseIsOverApple01 = false; }

//This is called when mouse is out of apple02 function mouseOutApple02 (event:MouseEvent):void { mouseIsOverApple02 = false; } //This function animates apple01 function enterFrameApple01 (event:Event):void { //If mouse is over the apple, decrease the blur if (mouseIsOverApple01 == true) { blur.blurX -= blurSpeed; blur.blurY -= blurSpeed; } /* If the mouse is out of the apple, and the blur is not over 20, we increase the blur. */ if (mouseIsOverApple01 == false && blur.blurX <= 20) { blur.blurX += blurSpeed; blur.blurY += blurSpeed; }

}

/* We need to assign the filter again since we made changes to the blur filter. */ apple01.filters = [blur];

//This function animates apple02 function enterFrameApple02 (event:Event):void { 100

//If mouse is over the apple, increase the blur until we reach if (mouseIsOverApple02 == true && bevelFilter.blurX < 100) { bevelFilter.blurX += bevelSpeed; bevelFilter.blurY += bevelSpeed; //We need to assign a strength to the bevel to make it

visible }

bevelFilter.strength = 5;

//If mouse is out of the apple02, decrease the blur if (mouseIsOverApple02 == false) { bevelFilter.blurX -= bevelSpeed; bevelFilter.blurY -= bevelSpeed; } /* If we are sure that no blur is applied, we make the whole bevel filter invisible (strength is 0). Otherwise we would see some ugly corners.

*/ if(bevelFilter.blurX == 0) { bevelFilter.strength = 0; } /* We need to assign the filter again since we made changes to the bevelFilter filter. */ apple02.filters = [bevelFilter]; }

You are done, test your movie! If you have any questions concerning this tutorial, please visit the forum. Have a nice day!

Main Menu •

Home 



Flash basics 



Actionscript 3.0 basics 



Actionscript 3.0 advanced 



Forum 



Contact 

Text Typing Effect

I'm sure you have seen many tutorials on how to create a text typing effect. These are mostly done by animating masks on the timeline. This tutorial is  a bit different. In this Actionscript 3 tutorial, you'll learn how to create a text effect as the user types some text. Check out the Flash movie above to see  how it looks (click on the movie and start typing). You can certainly customize the animation part to fit your taste, I'm just teaching how to set it up with  Actionscript 3.  Note: the movie supports Enter presses, but not erasing.

Setting up the environment  1. Create a new Flash document of size 400x400.  2. Create a dynamic text field. Apply the following settings. Note the instance name! 

3. Convert the text field into a movie clip. Set the registration point to the center. Name it "TextMC".  4. Linkage the movie clip to a class named "CharMovieClip".  5. Remove the movie clip from the stage. 

Moving into Actionscript  6. Open your actions panel and type the following. 

import fl.transitions.Tween; import fl.transitions.easing.*; //This variable stores the pressed key (String value) var pressedKey:String; //These are used for positioning a character on the stage var xpos:Number = 0; var ypos:Number = 0; //This is used for tracking the row number var rowNumber:uint = 0; //The height of a row var myRowHeight:uint = 30; /*

This us used for tracking how many characters there are in a row. */ var charactersOnRow:uint = 0; //This array holds all the tweens var tweens:Array = new Array(); //Listen when the user hits the keyboard stage.addEventListener (KeyboardEvent.KEY_DOWN, reportKeyDown); function reportKeyDown (event:KeyboardEvent):void { //Get the pressed key (String value) pressedKey = String.fromCharCode(event.charCode); //Get the key code var keyCode:int = event.keyCode; //ENTER is pressed, change the row //and exit the function if (keyCode == 13) { charactersOnRow = 0; rowNumber++; xpos = 0; ypos = myRowHeight * rowNumber; return; } //Create a new character movie clip var characterMC:CharMovieClip = new CharMovieClip(); //Call the function that writes the character in the movie clip writeCharacter (characterMC); /* If we have the maximum number of characters on a row, switch the row. */ if (charactersOnRow == 25) { charactersOnRow = 0; rowNumber++; xpos = 0; ypos = myRowHeight * rowNumber; } //Update the amount of characters there are in the current row charactersOnRow++; //Assign the correct position for the character characterMC.x = xpos + 10; characterMC.y = ypos + 10; //Update the x and y positions for the next character xpos += characterMC.width; ypos = myRowHeight * rowNumber; //Add the character movie clip to the stage

addChild (characterMC); //Call the function that animates the character animateCharacter (characterMC); } /* This function writes a character to the movie clip that is given as a parameter. */ function writeCharacter (characterMC:CharMovieClip):void { //Set the character on the movie clip's text field characterMC.myText.text = pressedKey;

}

//Make sure the character fits in the text field characterMC.myText.autoSize = TextFieldAutoSize.LEFT;

function animateCharacter (char:MovieClip):void { //Create a new movie clip, which we will animate var temp:CharMovieClip = new CharMovieClip(); //Write the typed character to the animated movie clip writeCharacter (temp); //Tween the movie clip var tweenX:Tween = new Tween(temp, "scaleY", Regular.easeOut, 0, 100, 1, true); var tweenY:Tween = new Tween(temp, "scaleX", Regular.easeOut, 0, 100, 1, true); var tweenAlpha:Tween = new Tween(temp, "alpha", Regular.easeOut, 1, 0, 0.5, true); //Push the tweens to an array, so they wont's get garbage collected tweens.push (tweenX); tweens.push (tweenY); tweens.push (tweenAlpha); //Assign the position temp.x = char.x; temp.y = char.y; //Add it to stage addChild (temp); }

Test your movie! If you have any questions, don't hesitate to ask in the forum. 

Actionscript 3 Snowfall Effect

This tutorial covers how you can create a snowfall effect using Actionscript 3.0. It could also be rain or something in between.  1. Create a new document of size 300x300.  2. Draw a shape that looks like a snowflake. My snowflake is of size 8x8. 3. Convert the shape into a movieclip (registration point at the top left corner).  4. Linkage the movie clip to a class called "Particle". 

5. Remove the snowflake from the stage. We're going to do all of the animation using actionscript. 6. Before we start to code the animation, create a Particle class (.as file) by typing the following (the Particle class represents the snowflake in the  tutorial). 

package { import flash.display.MovieClip; public class Particle extends MovieClip { //We need different speeds for different particles. //These variables can be accessed from the main movie, because they are public. public var speedX:Number; public var speedY:Number; function Particle ():void { } }

}

Remember to save this file ("Particle.as") in the same directory where the main movie is. 

7. Now in the main movie, type the following. 

var numberOfParticles:Number = 30; var particlesArray:Array = new Array(); //This loop creates 40 particles that are positioned randomly on the stage. for (var i=0; i < numberOfParticles; i++) { var particle:Particle = new Particle(); //Give random x and y speed to the particle. Math.random returns a random number n, where 0 <= n < 1. particle.speedX = Math.random(); particle.speedY = 3 + Math.random(); //Set the starting position particle.y = Math.random() * stage.stageHeight; particle.x = Math.random() * stage.stageWidth; //Set random alpha between 0.2 and 1 particle.alpha = 0.2 + Math.random() * 0.8; use.

//Add the particle to the stage and push it to array for later addChild (particle); particlesArray.push (particle);

} You should now have a similar setup, if you test your movie. 

8. Type the following code in the actions panel. 

addEventListener (Event.ENTER_FRAME, enterFrameHandler);

function enterFrameHandler (e:Event):void {

}

//Loop through the particles for (var i = 0; i < particlesArray.length; i++) { var particle = particlesArray[i]; particle.y += particle.speedY; particle.x += particle.speedX; }

If you test your movie, the particles move nicely to the bottom. The question is, what to do with them, after they fall of the screen. In this lesson, we'll  move a snowflake back to the top and start the falling again.  9. To achieve this, modify the enterFrameHandler so it looks like this.

function enterFrameHandler (e:Event):void { //Loop through the particles for (var i = 0; i < particlesArray.length; i++) { var particle = particlesArray[i]; particle.y += particle.speedY; particle.x += particle.speedX; to the top

//If the particle is below the bottom, position it back if (particle.y > stage.stageHeight) { particle.y = 0; particle.x = Math.random() * stage.stageWidth; }

}

}

10. I think have a pretty decent looking snowfall in our application. There are still two things I'd like to do. I want each snowball to differ in size and blur  some of them. 11. Type the following in the for loop, where we create the particles.

//Set a random scale to each particle. Scale is between 0.5 and 1.

particle.scaleX = 0.5 + Math.random() * 0.5; particle.scaleY = particle.scaleX;

//Create a blur effect in each snowflake var tempBlurAmount = Math.random()*4; var blur:BlurFilter = new BlurFilter(tempBlurAmount, tempBlurAmount, 1); var particleFilters:Array = new Array(); particleFilters.push (blur); particle.filters = particleFilters;

That wasn't so hard, was it? Remember, you can change the type of particle you want to animate. For water, you probably want to change the speeds  a bit higher. Play with the values and create your own rain effect! 

Final code var numberOfParticles:Number = 60; var particlesArray:Array = new Array(); //This loop creates 60 particles that are positioned randomly on top of the page. for (var i=0; i < numberOfParticles; i++) {

var particle:Particle = new Particle(); //Give random x and y speed to the particle. Math.random returns a random number n, where 0 <= n < 1. particle.speedX = Math.random(); particle.speedY = 3 + Math.random(); 1.

//Set a random scale to each particle. Scale is between 0.5 and particle.scaleX = 0.5 + Math.random() * 0.5; particle.scaleY = particle.scaleX;

//Create a blur effect in each snowflake var tempBlurAmount = Math.random()*4; var blur:BlurFilter = new BlurFilter(tempBlurAmount, tempBlurAmount, 1); var particleFilters:Array = new Array(); particleFilters.push (blur); particle.filters = particleFilters; //Set the starting position particle.y = Math.random() * stage.stageHeight; particle.x = Math.random() * stage.stageWidth; //Set random alpha between 0.2 and 1 particle.alpha = 0.2 + Math.random() * 0.8; use.

//Add the particle to the stage and push it to array for later addChild (particle); particlesArray.push (particle);

} addEventListener (Event.ENTER_FRAME, enterFrameHandler); function enterFrameHandler (e:Event):void { //Loop through the particles for (var i = 0; i < particlesArray.length; i++) { var particle = particlesArray[i]; particle.y += particle.speedY; particle.x += particle.speedX; to the top

//If the particle is below the bottom, position it back if (particle.y > stage.stageHeight) { particle.y = 0; particle.x = Math.random() * stage.stageWidth; }

}

}

Mask Home of Flash and Actionscript 3  Tutorials

Actionscript 3 Magnifying Glass Effect

1. Create a new document (size should be the same as the image's size you'll be using).  2. Import your image to the stage.  3. Convert the image into a movie clip called "backgroundImage".  4. Give the movie clip an instance name of "backgroundImage".  5. Duplicate the movie clip (backgroundImage), give the duplicate a name of "maskedImage".  6. Create a new layer called "masked image"

7. Drag the maskedImage onto the new layer. Give it an instance name of "maskedImage". Make sure the maskedImage is exactly on top of the  backgroundImage. 8. Now hide the "masked image" layer. 

9. Blur the backgroundImage to value 10. 

10. You can now view the maskedImage layer again. We'll soon move to actionscript, but before that, let's create the actual magnifying glass.  11. Create a new layer called "mask circle" and draw a circle of the height you want. I chose a radius of 50px.  12. Convert the circle into a movie clip "maskCircle"(registration point in the center). Give it an instance name of "maskCircle".  13. Now let's move over to actionscript. Create an actions layer and type the following.

//This set's the mask to the image. maskedImage.mask = maskCircle; //Let's hide the mouse Mouse.hide(); addEventListener(Event.ENTER_FRAME, enterFrameHandler); //In each frame, we want to move the circle to the place of the mouse function enterFrameHandler(e:Event):void { maskCircle.x = mouseX; maskCircle.y = mouseY; } Now test your movie. You should have a same looking effect as seen in the first page. Remember, you can do all sorts of masks, not just the  magnifying effect. For example, you could make the background completely black as I've done in the movie below. Play with this, and create  something new! 

Click the movie to see what happens. To create an effect like that, type the following. 

stage.addEventListener(MouseEvent.CLICK, clickHandler); //If the user click the mouse, expand the mask so that it reveals the whole image function clickHandler(e:Event):void { //Let's remove the old enterFrameHandler removeEventListener(Event.ENTER_FRAME, enterFrameHandler); //Add another ENTER_FRAME listener addEventListener(Event.ENTER_FRAME, scaleMask); //Show the mouse Mouse.show(); } //In each frame, increase the scale of the circle

function scaleMask(e:Event):void { maskCircle.scaleX += 0.2; maskCircle.scaleY += 0.2; }

Final code //This set's the mask to the image. maskedImage.mask = maskCircle; //Let's hide the mouse Mouse.hide(); addEventListener(Event.ENTER_FRAME, enterFrameHandler); //In each frame, we want to move the circle to the place of the mouse function enterFrameHandler(e:Event):void { maskCircle.x = mouseX; maskCircle.y = mouseY; } stage.addEventListener(MouseEvent.CLICK, clickHandler); //If the user click the mouse, expand the mask so that it reveals the whole image function clickHandler(e:Event):void { //Let's remove the old enterFrameHandler removeEventListener(Event.ENTER_FRAME, enterFrameHandler); //Add another ENTER_FRAME listener addEventListener(Event.ENTER_FRAME, scaleMask); //Show the mouse Mouse.show(); } //In each frame, increase the scale of the circle function scaleMask(e:Event):void { maskCircle.scaleX += 0.2; maskCircle.scaleY += 0.2; }

Actionscript 3 Image Mask Eraser 1. Import an image you want to use.  2. Convert the image into a movie clip (name it whatever you want).  3. Give it an instance name of "imageMC".  4. Create an actions layer and type the following. 

//This container contains all the mask graphics

var container:Sprite = new Sprite(); addChild (container); //Set the container to be the image's mask imageMC.mask = container; //Set the starting point container.graphics.moveTo (mouseX, mouseY); addEventListener (Event.ENTER_FRAME, enterFrameHandler); /*Draw a new rectangle in each frame and add it onto the container NOTE: you can use all kinds of shapes, not just rectangles! */ function enterFrameHandler (e:Event):void { container.graphics.beginFill(0xff00ff); container.graphics.drawRect(mouseX-50, mouseY-50, 100, 100); container.graphics.endFill(); } Mouse.hide(); 5. You are done, test your movie! 

Actionscript 3 Trail Effect

In this tutorial, you'll learn how to create a trail effect as seen in the movie above. All this is done via Actionscript 3.0 of course. The effect is quite  easily accomplished and it's very easy to modify the code to create different trail effects. Let's get started to create this Flash CS3 movie!

Setting up the environment

1. Create a new Flash Actionscript 3.0 document of size 300x300.  2. Draw a circle of size 30x30 (you can choose the colors as you like).  3. Convert the circle into a movie clip (name doesn't matter, registration point in the center). 4. Give the ball an instance name of "ball".  5. Linkage the ball movie clip to a class called "Ball".  6. Leave the ball on the stage (position doesn't matter). 

Moving into Actionscript 3.0 Type the following in the first frame of your movie. 

//Define the starting angle var angle:Number = 0; //Define the rotation speed var speed:Number = 0.2; //Define the circle's radius var radius:Number = 50; /* We want the ball to rotate around the center of the stage. We declare variables for the center coordinates, so they don't need to be calculated again in each frame (this saves time from CPU). */ var centerX:Number = stage.stageWidth / 2; var centerY:Number = stage.stageHeight / 2; //Add ENTER_FRAME to the ball, so we can animate it in each frame ball.addEventListener (Event.ENTER_FRAME, moveBall); //We use this timer to create a trail ball each 0.1 seconds var timer:Timer = new Timer(100,400000); timer.addEventListener (TimerEvent.TIMER, createTrailBall); timer.start (); //This function is responsible for moving the ball function moveBall (e:Event):void { //Calculate the new x and y coordinates var xpos:Number = centerX + Math.cos(angle) * radius; var ypos:Number = centerY + Math.sin(angle) * radius; //Move the ball to the new coordinates ball.x = xpos; ball.y = ypos; //Increase the angle angle += speed; } function createTrailBall (e:Event):void {

//Create a new ball instance var trailBall:Ball=new Ball(); //Position the trail ball in the same position where the original ball is located trailBall.x = ball.x; trailBall.y = ball.y; //Add ENTER_FRAME to animate the trail ball trailBall.addEventListener (Event.ENTER_FRAME,animateTrailBall);

ball.

}

/* Add the trail ball on to the stage. We don't want to position the trail ball on top of the original We use the addChildAt method to set the index to 0. */ addChildAt (trailBall,0);

function animateTrailBall (e:Event):void { //In each frame, reduce the alpha and the scale of the trail ball. e.target.alpha -= 0.04; e.target.scaleY -= 0.04; e.target.scaleX -= 0.04; /* If the alpha is less than 0, we remove the trail ball from the stage. */ if (e.target.alpha < 0) { e.target.removeEventListener (Event.ENTER_FRAME,animateTrailBall); removeChild ((MovieClip)(e.target)); } } The code is pretty straightforward. The comments should be informative enough to let you know what we're doing in each step. As you can see, the  values can be easily changed to create different kinds of trail effects. For example, in the following movie, I just changed the timer to create a trail ball  every 0.02 seconds.

var timer:Timer = new Timer(20,400000);

That's it for this Actionscript 3.0 tutorial. Hope you enjoyed it and learned something new! If you have any questions concerning the tutorials, please  visit the forum. 

Actionscript 3 Shake Effect

In this tutorial, I'll show you how you can create a shake effect as seen in the movie above. All this is done via Actionscript 3.0 of course. So start your  Flash and let's get started.

Setting up the environment 1. Create a new Flash Actionscript 3.0 document of size 300x300.  2. Draw a rectangle on the stage.  3. Convert the rectangle into a movie clip (name doesn't matter, registration point in the center). 4. Linkage the rectangle movie clip to a class named "Rectangle". 5. Remove the rectangle from the stage. We'll be adding all of the rectangles to the stage via Actionscript 3.0.

Moving into Actionscript 3.0  Type the following in the first frame of your movie. 

//This array will hold all the rectangles on the stage var rectangles:Array = new Array(); //In this loop, we'll create 20 rectangles for (var i = 0; i < 20; i++) { //Create one rectangle var rectangle:Rectangle = new Rectangle(); //Assign a random scale for the rectangle (scaleX and scaleY are the same) rectangle.scaleX = Math.random(); rectangle.scaleY = rectangle.scaleX; //Assign a random position rectangle.x = Math.random() * stage.stageWidth; rectangle.y = Math.random() * stage.stageHeight; //Add the rectangle on to the stage addChild (rectangle);

}

//Add the rectangle to the array rectangles.push (rectangle);

//The timer will call the "shakeRectangles" function every 0.02 seconds var timer:Timer = new Timer(20, 100000000); timer.addEventListener (TimerEvent.TIMER, shakeRectangles); timer.start (); //This function is responsible for animating the shake function shakeRectangles (e:Event):void { //Loop through the array for (var i = 0; i < 20; i++) { //Rotate the rectangle a random amount (from -4 to 4) rectangles[i].rotation += Math.random() * 8 - 4;

//Assign a new random position rectangles[i].x += Math.random() * 8 - 4; rectangles[i].y += Math.random() * 8 - 4; }

}

That wasn't hard at all, was it? Go ahead and play with this by changing the values and shapes. Hope you learned something new from this! 

Boxes Avoiding Getting Hit

In this Actionscript 3 tutorial, I will show you how to create boxes that will avoid being hit by a ball. The end result is seen above (click the white ball to  launh the movie). Let's get started straight away! 

Setting up the environment  1. Create a new Flash Actionscript 3 movie (340x200).  2. Draw a rectangle on the stage. Make it size 20x20.  3. Convert the rectangle into a movie clip. Name it however you want, just set the registration point to the center! 4. Linkage the movie clip to a class named "Box". If you are unfamiliar with movie clip linkage, check the Actionscript 3 External Classes tutorial. 5. Now draw a circle of size 10x10 on the stage.  6. Convert the circle into a movie clip. Name it however you want, just set the registration point to the center! 7. Linkage the circle movie clip to a class named "Ball".  8. Remove the circle and the rectangle from the stage.

Moving into Actionsctipt

9. Type the following Actionscript code in the first frame. 

//This array will hold all the boxes var boxes:Array = new Array(); //Set the ball's speed var ballSpeed:Number = -4; //This loop adds 8 boxes to the stage for (var i = 0; i < 9; i++) { //Create a box var box:Box = new Box(); //Assign a position box.y = 150; box.x = box.width * i * 1.5 + 40; //Add the box to the array boxes.push(box); //Add the box to the stage addChild(box); } //Create the ball and set it to the right side var ball:Ball = new Ball(); ball.x = 320; ball.y =155; //Make the ball look like a button (hand cursor) ball.buttonMode = true; //Add the ball to the stage addChild(ball); //Listen when the user clicks the ball ball.addEventListener(MouseEvent.CLICK, ballClicked); //This function is called when the user clicks the ball function ballClicked(e:Event):void {

}

//Add ENTER_FRAME which does all the animation addEventListener(Event.ENTER_FRAME, enterFrameHandler);

//This function is called in every frame function enterFrameHandler(e:Event):void { //Move the ball to the left by 2 pixels ball.x += ballSpeed; for (var i = 0; i < boxes.length; i++) { //Get a box from the array var box:Box = boxes[i] as Box;

//Check the x distance from the ball to the box var distX:Number = ball.x - box.x; //Ball is coming from the right if (distX < 50 && distX > 0 && ballSpeed < 0) { //Animate box up box.y -= 2; } //Ball is leaving to the left else if (distX < 50 && distX < 0 && ballSpeed < 0) { //Animate the ball down if it's not in original position

if (box.y <= 150) { box.y += 2; } } //Ball is coming from the left if (distX < 0 && distX > -50 && ballSpeed > 0) { //Animate box up box.y -= 2; } //Ball is leaving to the right else if (distX < 50 && distX > 0 && ballSpeed > 0) { //Animate the ball down if it's not in original

position

if (box.y <= 150) { box.y += 2; } } //Move the direction if the ball is over to the left //or right edge. if (ball.x + 5 >stage.stageWidth || ball.x - 5 < 0) {

} }

//Invert the speed ballSpeed *= (-1);

}

Test your movie! I hope you learned something new from this. Remember, if you have any questions, don't hesitate to ask in the forum.

}

//Don't listen this function anymore stage.removeEventListener(MouseEvent.CLICK, clickedAnimateBack);

//This function animates the images to original positions function animateBack():void { //Loop thorugh the images for (var i = 0; i < imagePieceHolders.length; i++) { //Get the image from the array

var imagePiece:MovieClip = (MovieClip)(imagePieceHolders[i]); //Move to the original x position var tweenX:Tween = new Tween(imagePiece, "x", Regular.easeOut, imagePiece.x, imagePiece.origX, Math.random(), true); //Move to the original y position var tweenY:Tween = new Tween(imagePiece, "y", Regular.easeOut, imagePiece.y, imagePiece.origY, Math.random(), true); //Add the tweens into the array tweens.push(tweenX); tweens.push(tweenY); } //Listen for the user's click stage.addEventListener(MouseEvent.CLICK, clicked); }

You can test your movie now! The comments should be informative enough to let you know what we are doing in 

Image Animation via Actionscript 3

Click the stage to see what happens, then click it again :) I bet that you are wondering how the above flash movie is done. We'll, that's what we are  here to find out! 

Setting up the environment  1. Get yourself a nice image. The only restriction is, that it must be the size of 300x300.  2. Save the image to the same folder where you will save your FLA file. 

Moving into Actionscript 3. Type the following Actionscript 3 code in the first frame. 

import fl.transitions.Tween; import fl.transitions.easing.*; //This array will hold all the image pieces var imagePieceHolders:Array = new Array(); //We add our tweens to this array, so they don't //get garbage collected var tweens:Array = new Array(); //Create a loader that loads the image var imageLoader:Loader = new Loader(); imageLoader.load(new URLRequest("http://flashmymind.com/SWF/myImage.gif")); //Listen when the loading is done imageLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, completeHandler); //This function is called when the image is loaded. //Then we slice the image into 30x30 pieces //and add the pieces to the stage. function completeHandler(event:Event):void { //Get the image from the loader var imageTextureMap:BitmapData = event.target.content.bitmapData; //Loop through the colums for (var i = 0; i < 10; i++) { //Loop through the rows for (var j = 0; j < 10; j++) { piece

//Create a new movieclip that holds an image var imagePieceHolder:MovieClip = new MovieClip(); //Create a new bitmap of size 30x30

var imagePiece:Bitmap = new Bitmap(); imagePiece.bitmapData = new BitmapData(30, 30); //Copy pixels (30x30 rectangular area) from the orginal image

imagePiece.bitmapData.copyPixels(imageTextureMap, new Rectangle(i * 30, j * 30, 30, 30), new Point(0, 0)); //Add the image piece to the movie clip holder imagePieceHolder.addChild(imagePiece); //Position the image holder to the stage imagePieceHolder.x = i * 30; imagePieceHolder.y = j * 30;

in the animation)

//Store the original position (we need this later imagePieceHolder.origX = imagePieceHolder.x; imagePieceHolder.origY = imagePieceHolder.y; //Add the imagePiece holder to the stage addChild(imagePieceHolder); //Add the imagePiece holder to the array imagePieceHolders.push(imagePieceHolder);

}

}

} //Listen for the user's click stage.addEventListener(MouseEvent.CLICK, clicked); //This is called when the user clicks the stage function clicked(e:MouseEvent):void { //Call the function that animates the image pieces animateAway();

}

//Remove this function listener stage.removeEventListener(MouseEvent.CLICK, clicked);

//This function animates the image pieces to random positions function animateAway():void { //Loop through the array of images for (var i = 0; i < imagePieceHolders.length; i++) { //Get the image from the array var imagePiece:MovieClip = (MovieClip)(imagePieceHolders[i]); //Tween to random x position with random time var tweenX:Tween = new Tween(imagePiece, "x", Regular.easeOut, imagePiece.x, Math.random() * 300,

Math.random(), true); //Tween to random y position with random time var tweenY:Tween = new Tween(imagePiece, "y", Regular.easeOut, imagePiece.y, Math.random() * 300, Math.random(), true); //Push the tweens into an array tweens.push(tweenX); tweens.push(tweenY); //Listen when the user clicks the stage stage.addEventListener(MouseEvent.CLICK, clickedAnimateBack); } } //This is called when the user clicks the stage (when //the images have already animated) function clickedAnimateBack(e:MouseEvent):void { //Call the function that animates the images back animateBack();

}

//Don't listen this function anymore stage.removeEventListener(MouseEvent.CLICK, clickedAnimateBack);

//This function animates the images to original positions function animateBack():void { //Loop thorugh the images for (var i = 0; i < imagePieceHolders.length; i++) { //Get the image from the array var imagePiece:MovieClip = (MovieClip)(imagePieceHolders[i]); //Move to the original x position var tweenX:Tween = new Tween(imagePiece, "x", Regular.easeOut, imagePiece.x, imagePiece.origX, Math.random(), true); //Move to the original y position var tweenY:Tween = new Tween(imagePiece, "y", Regular.easeOut, imagePiece.y, imagePiece.origY, Math.random(), true); //Add the tweens into the array tweens.push(tweenX); tweens.push(tweenY); } //Listen for the user's click

}

stage.addEventListener(MouseEvent.CLICK, clicked);

You can test your movie now! The comments should be informative enough to let you know what we are doing in each step. Here is the BIG IDEA if  you still have some doubts: 

Actionscript 3 Image Mask Animation

1. Make/download an image of size 500x300. 2. Create a new document (500x300). 3. Import your image into the library.  4. Drag that image to the stage (add it to the center of the stage). 5. Convert it into a movieclip.

6. Give your movie clip an instance name.

7. Now we are ready to make the boxes that reveal the picture. Draw a rectangle shape (can be on the same layer, position doesn’t matter). No  borders! 8. Make the rectangle to size 40x40. 9. Convert the rectangle into a movie clip. Note the registration point!

10. Remove the rectangle from the stage. 11. Linkage the rectangle to a class ”MaskRectangle”. 

Don’t worry about the warning above .

12. Now we start to use actionscript. Via actionscript, we organize the mask boxes onto the image and then tween them to reveal the image. 13. Create an actions layer, type the following.

var boxWidth:Number = 40; var boxHeight:Number = 40; var rows:Number = 6; var columns:Number = 10; var boxes:Array = new Array(); var tweens:Array = new Array(); var container:Sprite = new Sprite(); addChild(container); for (var i=0; i Explanation: First, we declare some variables. We want 6 rows and 10 colums for this image to animate nice. We want to use a container, where we  add the boxes (=MaskRectangle). This is done, because a movie clip can only have one mask (we can’t add the boxes separately onto the image to 

act as a mask). Eventually, we’ll mask the image with the container. In the for loop, we simply organize the boxes row by row. We push all the boxes  into an array for later use.

14. Next we set up the mask and scale the boxes. Type the following. 

cityMC.mask = container; for (var k=0; k< boxes.length; k++) { boxes[k].scaleX = 0; } Explanation: We assign the container to be the image’s mask. Then we change the scaleX property, so the boxes will be invisible at the beginning of  the animation.

15. Now for the animation part, type the following.

var timer = new Timer(35,boxes.length); timer.addEventListener (TimerEvent.TIMER, animateMask); timer.start (); function animateMask (e:Event):void { var box = boxes[timer.currentCount-1]; var myTween:Tween = new Tween(box, "scaleX", Bounce.easeOut, 0, 1, 1, true); tweens.push(myTween); } Note: You must add the following import statements.

import fl.transitions.Tween; import fl.transitions.easing.*; Explanation: First we create a timer. Our delay is 35 milliseconds and we call the timer as many times as we have boxes. We add an event listener,  which is called every 35 milliseconds. Then we start the timer. In the event handler, we check which box we should animate. Then, we apply a motion  tween with bounce effect. We push the tweens into an array, so they won’t get garbage collected. That’s all!

16. Test your movie. Remember, you are not restricted to just rectangles or bounce effect. You can also change the order of how you animate the boxes. Play with it. If you  have any questions concerning the tutorials, please visit the forum.

Final code  import fl.transitions.Tween; import fl.transitions.easing.*; var boxWidth:Number = 40;

var boxHeight:Number = 40; var rows:Number = 6; var columns:Number = 10; var boxes:Array = new Array(); var tweens:Array = new Array(); var container:Sprite = new Sprite(); addChild(container); for (var i=0; i< boxes.length; k++) { boxes[k].scaleX = 0; } var timer = new Timer(35,boxes.length); timer.addEventListener (TimerEvent.TIMER, animateMask); timer.start (); function animateMask (e:Event):void { var box = boxes[timer.currentCount-1]; var myTween:Tween = new Tween(box, "scaleX", Bounce.easeOut, 0, 1, 1, true); tweens.push(myTween); }

Actionscript 3 Fireworks

Intro 

This tutorial teaches you how to create random fireworks via Actionscript 3.0. There is quite a bit of code here, but it's all really simple, if you just think  about it for a while. For this tutorial, we'll be using two external actionscript 3.0 classes and the main movie.

Setting up the environment  1. Create a new document of size 300x300.  2. Draw a ball of size 15x15 (you can choose the color as you like).  3. Convert it into a movie clip (registration point in the center). 4. Linkage to movie clip to a class called "Particle".  5. Remove the Particle from the stage. 

Moving into Actionscript 3.0  First, let's set up the main movie. Type the following in the actions panel (in the first frame). 

/* This timer runs 2000 times every 0.5 seconds. */ var myTimer:Timer = new Timer(500, 2000); myTimer.addEventListener (TimerEvent.TIMER, timerHandler); myTimer.start (); /* This function is called every 0.5 seconds. */ function timerHandler (event:TimerEvent):void { //Create a new firework var firework:Firework = new Firework(); //Set a random x position firework.x = Math.random() * stage.stageWidth; //Set it to be at the bottom of the stage. firework.y = stage.stageHeight;

}

//Add it to the stage addChild (firework);

Now let's create the firework class. Create a new actionscript 3.0 file (.as) and name it "Firework". In the file, type the following. 

package { import import import import /*

flash.utils.Timer; flash.events.TimerEvent; flash.display.MovieClip; flash.events.*;

This class represents one firework that starts to move upwards and then explodes. */ public class Firework extends MovieClip { //Each firework has its own speed private var speedY:Number = 0; private var timer:Timer; function Firework ():void { //Assign a random y speed speedY = (-1) * Math.random() * 2 - 2; //Draw the firework (you could also use an image or something more fancy) graphics.beginFill (0xffffff); graphics.drawCircle (0, 0, 2); graphics.endFill (); //We want the firework to immediately start

moving upwards }

takeOff();

//This function adds event listeners for the animation private function takeOff ():void { takeOffEnterFrame);

addEventListener (Event.ENTER_FRAME, /* Add a timer so we know when to make an explosion. In this case the firework explodes after 2

seconds.

*/ timer = new Timer(2000,1); timer.start (); timer.addEventListener (TimerEvent.TIMER_COMPLETE, explode); } //Firework moves up... private function takeOffEnterFrame (e:Event):void { this.y += speedY; } /* This function is called when the timer is finished. That's when we want to explode the firework. */ private function explode (e:Event):void { //Remove the take off animation removeEventListener (Event.ENTER_FRAME, takeOffEnterFrame);

//Create an explosion to the same position as where this firework is

var explosion:Explosion = new Explosion(); explosion.x = this.x; explosion.y = this.y; //Add the explosion to stage stage.addChild (explosion);

//Make the firework invisible, we don't want to show it when the explosion starts this.visible = false; }

}

} We are almost done. We still need to create the Explosion class, which will be responsible for the whole explosion animation. Create a new actionscript file and name it "Explosion". Type the following. 

package { import import import import import import

flash.utils.Timer; flash.events.TimerEvent; flash.display.MovieClip; flash.events.*; fl.motion.Color; flash.geom.ColorTransform;

/* This class represents the explosion that starts from the firework. */ public class Explosion extends MovieClip { private var particlesArray:Array; private var numberOfParticles:uint = 0; function Explosion ():void { exploded particles

//Create a new array where to put all the particlesArray = new Array();

(10-40 particles) 30) + 10;

//Explosions have a random number of particles numberOfParticles = Math.floor(Math.random() * //Assign a random color for explosion var ct:Color = new Color(); ct.setTint (0xFFFFFF * Math.random(),1);

different size

//We use the scale to make the particles of var scale:Number = Math.random();

particles.

/* We want the particles to explode in circle. We calculate the angle difference between the */ var angleDifference:Number = 360 /

numberOfParticles;

var angle = 0; for (var i = 0; i < numberOfParticles; i++) { var particle:Particle = new Particle();

//Each particle gets exploded into the direction specified by the angle particle.speedY = Math.sin(angle * Math.PI/180)*3; particle.speedX = Math.cos(angle * Math.PI/180)*3; //Assign the scale to change the

particle's size

particle.scaleX = scale; particle.scaleY = scale; particlesArray.push (particle); //Assign the color particle.transform.colorTransform = ct; addChild (particle); //Update the angle for the next particle angle += angleDifference;

} addEventListener (Event.ENTER_FRAME,

enterFrameHandler); } function enterFrameHandler (e:Event):void { for (var i = 0; i < particlesArray.length; i++) { var particle:Particle = particlesArray[i]; //Update y and x coordinates particle.y += particle.speedY; particle.x += particle.speedX; //Fade away the particle particle.alpha -= 0.02; //Remove the explosion animation when all the particles are invisible

if (particle.alpha < -0.1) {

removeEventListener (Event.ENTER_FRAME, enterFrameHandler); } } } } } You're done, test your movie! Feel free the copy this code and modify it to your own needs. You might for example change the boring white dots to  something more interesting. I hope you found this tutorial useful! 

Actionscript 3 Random Circles on Image

In this tutorial, you'll learn how to create the above mask effect just by using Actionscript 3.0. Let's get started with Flash CS3!

Setting up the environment 1. Create a new Flash Actionscript 3.0 document of size 300x300.  2. Import an image of size 300x300 to the center of the stage.  3. Convert the image into a movie clip (name doesn't matter, registration point in the center). 4. Give the image movie clip an instance name of "picture". 5. Draw a circle shape on the same layer as the picture.  6. Convert the circle into a movie clip (name doesn't matter, registration point in the center).  7. Remove the cirlce from the stage. 

8. Linkage the circle movie clip to a class named "MaskBall". These MaskBalls are the circles, that will slowly uncover the image.

Moving into Actionscript 3.0 Create a new layer called "actions". Type the following in the first frame. 

//This container contains all the circles that act as a mask for the picture var container:Sprite = new Sprite(); //Assign the container to be the image's mask picture.mask = container; //Add the container to the stage addChild (container); /* This timer is responsible for creating a circle every 0.05 seconds. A total of 20 circles will be created. */ var timer = new Timer(50,20); timer.addEventListener (TimerEvent.TIMER, createMaskBall); timer.start (); //The timer calls this function every 0.05 seconds function createMaskBall (e:Event):void { //Create a new MaskBall var maskBall:MaskBall = new MaskBall(); //Set scale to zero so it won't be visible at the beginning maskBall.scaleX = 0; maskBall.scaleY = 0; //Assign a random position in the stage maskBall.x = Math.random() * stage.stageWidth; maskBall.y = Math.random() * stage.stageHeight; //Add the maskBall to the container container.addChild (maskBall); //We need ENTER_FRAME function to handle the animation maskBall.addEventListener (Event.ENTER_FRAME, animateMaskBall); } //This function is called in every frame function animateMaskBall (e:Event):void { //Increase the scale e.target.scaleX += 0.05; e.target.scaleY += 0.05; } That's it, test your movie! As you can see, it's much more efficient to create effects like this with actionscript rather than using a timeline. Hope you  enjoyed! If you have any questions concerning the tutorials, please visit the forum.

Actionscript 3 TransitionManager

This tutorial is all  about the Actionscript 3.0 TransitionManager. I will explain briefly what the TransitionManager class is and how you can use it your Flash movies. At  the end of this tutorial, you'll be able to create a movie as seen above. 

Intro The TransitionManager class allows you to apply different animation effects to movie clips. Overall, there are ten different animations available. These  are: Blinds, Fade, Fly, Iris, Photo, PixelDissolve, Rotate, Squeeze, Wipe and Zoom. You can see these in action in the movie above. 

Setting up the environment  1. Create a new document of size 500x300.  2. Draw a rectangle of size 50x50.  3. Convert the rectangle into a movie clip. Name it "box" and set the registration point to the center.  4. Now drag 10 of these movie clips on to the stage.  5. Give them instance names of "box1", "box2", box3", ... , "box10". 

Moving into Actionscript 3.0 

6. Create a new layer for actionscript and type the following. 

//We need for the animations import fl.transitions.*; import fl.transitions.easing.*; //This array will store all the transitions var transitions:Array = new Array(); //Add MOUSE_OVER handlers to each box box1.addEventListener (MouseEvent.MOUSE_OVER, mouseOverBox); box2.addEventListener (MouseEvent.MOUSE_OVER, mouseOverBox); box3.addEventListener (MouseEvent.MOUSE_OVER, mouseOverBox); box4.addEventListener (MouseEvent.MOUSE_OVER, mouseOverBox); box5.addEventListener (MouseEvent.MOUSE_OVER, mouseOverBox); box6.addEventListener (MouseEvent.MOUSE_OVER, mouseOverBox); box7.addEventListener (MouseEvent.MOUSE_OVER, mouseOverBox); box8.addEventListener (MouseEvent.MOUSE_OVER, mouseOverBox); box9.addEventListener (MouseEvent.MOUSE_OVER, mouseOverBox); box10.addEventListener (MouseEvent.MOUSE_OVER, mouseOverBox); //Assign a different transition to each box box1.transition = Blinds; box2.transition = Fade; box3.transition = Fly; box4.transition = Iris; box5.transition = Photo; box6.transition = Rotate; box7.transition = Squeeze; box8.transition = Wipe; box9.transition = PixelDissolve; box10.transition = Zoom; //This function is called everytime the mouse moves over a box function mouseOverBox (e:Event):void { //Store the selected box in a local variable var selectedBox:MovieClip = MovieClip(e.target); //Remove the event listener (the user can't stop the animation once started) selectedBox.removeEventListener (MouseEvent.MOUSE_OVER, mouseOverBox); /* Start a new transition with the following parametes type: We use a transition type that is defined for each box direction: The direction of the animation (Transition.OUT is the second option) duration: Duration of the animation in seconds easing: The type of easing applied to the animation shape: A mask shape. Applies only when using the "Iris" transition */ var myTransitionManager:TransitionManager = new TransitionManager(selectedBox);

myTransitionManager.startTransition ({type:selectedBox.transition, direction:Transition.IN, duration:1, easing:Regular.easeOut, shape:Iris.CIRCLE}); //Add the transition to an array, so it won't get garbage collected transitions.push(myTransitionManager); //Add a listener that calls the function animationComplete, when the animation is finished myTransitionManager.addEventListener ("allTransitionsInDone", animationComplete); } //This function is called when a box animation is complete function animationComplete (e:Event):void { //Start listening for the MOUSE_OVER again e.target.content.addEventListener (MouseEvent.MOUSE_OVER, mouseOverBox); } You are done, test your movie! I must say a couple of words about the "allTransitionsInDone" event. If look for it in the Adobe documentation, you won't  find it. It is a very useful event and I strongly believe it should be documented as well. For more information about the event, see the comments section  in TransitionManager ­ Actionscript 3 Language and Components Reference. If you have any questions concerning the tutorial, don't hesitate to ask in the forum. 

Actionscript 3 Fountain

After this lesson, you'll be able to create a movie as seen above. Move your mouse up and down on the stage to see how the fountain reacts. This  tutorial is pretty easy to follow, since there is only Actionscript 3.0 involved. All of the shapes and such are created using simple actionscript code :) .  So let's get started!

Setting up the environment  1. Create a new document of size 300x300.  That's it. We're ready to move into actionscript. 

Moving into Actionscript 3.0  Type the following. 

/* Define the gravity. This determines how fast the balls are pulled down. */ var gravity:Number = 0.4; //Create 128 balls in the for-loop (change this to whatever you want) for (var i = 0; i < 128; i++) { //Create a ball var ball:MovieClip = new MovieClip(); //Call the function that draws a circle on the ball movie clip drawGraphics (ball); //Initial position of the ball ball.x = stage.stageWidth / 2;

ball.y = stage.stageHeight; //Define a random x and y speed for the ball ball.speedX = Math.random() * 2 - 1; ball.speedY = Math.random() * -8 - 4; //Add the ball to the stage addChild (ball);

}

//ENTER_FRAME function is responsible for animating the ball ball.addEventListener (Event.ENTER_FRAME, moveBall);

/* This function is responsible for drawing a circle on a movie clip given as parameter */ function drawGraphics (mc:MovieClip):void { //Give a random color for the circle mc.graphics.beginFill (0xffffff * Math.random()); //Draw the cirlce mc.graphics.drawCircle (0, 0, 3);

}

//End the filling mc.graphics.endFill ();

This piece of code "initializes" our setup. To get the animation in your movie, type the following. 

//This function is responsible for animation a ball function moveBall (e:Event):void { //Let's assign the ball to a local variable var ball:MovieClip = (MovieClip)(e.target); //Apply gravity tot the y speed ball.speedY += gravity; //Update the ball's postion ball.x += ball.speedX; ball.y += ball.speedY; //Chech if the ball has gone under the stage if (ball.y > stage.stageHeight) { /* Calculate the mouse height. We use the mouse height to give the ball a new random y speed

*/ var mouseHeight:Number = stage.stageHeight - mouseY; //Calculate the new y speed var newSpeedY = Math.random() * (-mouseHeight * 0.05);

//Move the ball to the initial position ball.x = stage.stageWidth / 2; ball.y = stage.stageHeight; //Assign the new calculated random speeds for the ball ball.speedX = Math.random() * 2 - 1; ball.speedY = newSpeedY; }

}

That's it, test your movie!

Actionscript 3 Falling Bits

In this tutorial, I'll show you how to create bits that are falling out of the screen. All animation is done via Actionscript 3.0, so no timeline animation will  be included. 

Setting up the environment  1. Create a new document of size 300x300.  2. Create a dynamic text field. Type in a number, eg. 1. 3. Give it an instance name of "myText". Set the font to 15.  4. Click the Embed button and embed the numerals. 

5. Convert the text field into a movieclip. Name it "numberInsideMC". Set the registration point to the top left corner.  6. Give the movie clip an instance name of "numberInside".  7. Convert the "numberInsideMC" into a movie clip (just click it and press F8). Give the new movie clip a name "myNumberMC". Set the registration  point to the top left corner.  8. Linkage the "myNumberMC" to a class called "BitNumber". 

Moving into Actionscript 3.0  9. In the main timeline, create a new layer for actionscript. Type the following. 

//This array will contain all the numbers seen on stage var numbers:Array = new Array(); //We want 8 rows for (var i=0; i < 8; i++) { //We want 21 columns for (var j=0; j < 21; j++) { //Create a new BitNumber var myNumber:BitNumber = new BitNumber(); //Assign a starting position myNumber.x = myNumber.width * j; myNumber.y = myNumber.height * i; //Give it a random speed (2-7 pixels per frame) myNumber.speedY = Math.random() * 5 + 2; //Add the number to the stage addChild (myNumber); //Add the number to the array numbers.push (myNumber); }

}

//Add ENTER_FRAME so we can animate the numbers (move them down) addEventListener (Event.ENTER_FRAME, enterFrameHandler); /* This function is repsonsible for moving the numbers down the stage. The alpha animation is done inside of the myNumberMC movieclip. */ function enterFrameHandler (e:Event):void { //Loop through the numbers for (var i = 0; i < numbers.length; i++) { //Update the y position numbers[i].y += numbers[i].speedY; //If the BitNumber is below the stage, move it up again if (numbers[i].y > stage.stageHeight) { numbers[i].y = 0; } }

}

10. We are almost done, but we still need to add some code inside of our myNumberMC movie clip. Double click the myNumberMC and create a new  layer for actionscript.  11. Type the following in the actions panel. 

//This variable tells us should we increase the alpha var increaseAlpha:Boolean; //We want the number to be invisible at the beginning numberInside.alpha = 0; //Calculate a random timer delay (how often we increase the alpha) var timerDelay:Number = Math.random() * 4000 + 2000; //Create and start a timer var timer:Timer = new Timer(timerDelay, 0); timer.addEventListener (TimerEvent.TIMER, timerHandler); timer.start (); //Add ENTER_FRAME so we can animate the alpha change addEventListener (Event.ENTER_FRAME, enterFrameHandler); /* Timer calls this function. Timer delay defines how often this is called. */ function timerHandler (e:Event):void { //Update the increaseAlpha value increaseAlpha = true; //Calculate a random number (0 or 1) var newNumber:int = Math.floor(Math.random() * 2); //If the random number is 1, we insert "1" into the text box if (newNumber == 1) { numberInside.myText.text = "1"; } //Else we insert "0" into the text box else { numberInside.myText.text = "0"; } } //This function animates the alpha function enterFrameHandler (e:Event):void { //Increase the alpha if increaseAlpha is true if (increaseAlpha == true) { numberInside.alpha += 0.02; } //Else we want to decrease the alpha else { numberInside.alpha -= 0.02; }

//We don't want the alpha to be over one, so we assign increaseAlpha to be false if (numberInside.alpha > 1) { increaseAlpha = false; } //If the alpha is negative, set it to zero if(numberInside.alpha < 0) { numberInside.alpha = 0; } } 12. Go back to your main timeline and remove the myNumberMC from the stage. Your stage should now be empty.  13. Test your movie! 

Actionscript 3 Physics This tutorial is for anyone who wants to learn how to animate objects with the help of some simple physics. All done by Actionscript 3.0 of course. 1. Create a new document of size 400x400. 2. Draw a ball on the stage. Convert it into a movie clip (registration point in the center). 3. Give the ball an instance name of ”gameBall”. 4. Let’s set up the ball’s starting position. Type the following in the actions panel.

//Set the starting position of the ball to the center of the stage. gameBall.x = stage.stageWidth / 2; gameBall.y = stage.stageHeight / 2;

You should now have somewhat similar looking setup, if you’ll test your movie. Don’t worry if your colors are different. The ball could also be any size  you want. My gameBall is 50x50. 5. Let’s start adding some movement to our ball. Type the following 

//Declare variables var speedY:Number = var speedX:Number = var radius:Number = var friction:Number

needed for the physics (some are for later use). 0; 0; gameBall.height / 2; = 0.98;

//Acceleration variables var ax:Number = 0; var ay:Number = 0; var gravity:Number = 0.5; //Add event handler addEventListener (Event.ENTER_FRAME, enterFrameHandler); //This function is responsible for the whole animation in this movie. function enterFrameHandler (e:Event):void { //In each frame, add the necessary "forces" that moves the gameBall speedY += gravity; gameBall.y += speedY; }

Now our ball is falling as the gravity affects it. There is one problem though, the ball disappears as we reach the bottom. Let’s fix that. 6. Replace the enterFrameHandler with this new version 

function enterFrameHandler (e:Event):void { //In each frame, add the necessary "forces" that moves the "gameBall" speedY += gravity; gameBall.y += speedY; //Let's check when the ball hits the bottom. if(gameBall.y + radius > stage.stageHeight) { //When we hit the bottom, reposition the ball to be exactly on the //bottom edge. Change the sign of the speedY so we go to the other direction. gameBall.y = stage.stageHeight - radius; speedY *= -1; } }

Now we have a bouncing ball! 7. Let's allow the user to move the ball. Add the following code below the enterFrameHandler. 

//Add event listeners for the user's key presses stage.addEventListener (KeyboardEvent.KEY_DOWN, keyDownHandler); stage.addEventListener (KeyboardEvent.KEY_UP, keyUpHandler); function keyDownHandler (e:KeyboardEvent):void { switch (e.keyCode) { //User pressed the left arrow --> x acceleration negative

case Keyboard.LEFT : ax = -0.5; break; //User pressed the right arrow --> x acceleration

positivve

case Keyboard.RIGHT : ax = 0.5; break;

//User pressed the up arrow --> y acceleration negative (go up). Apply no gravity when up key down. case Keyboard.UP : gravity = 0; ay = -0.5; break;

//User pressed the down arrow --> y acceleration positivve

}

case Keyboard.DOWN : ay = 0.5; break;

}

function keyUpHandler (e:KeyboardEvent):void { gravity = 0.5; ax = 0; ay = 0; } Modify the enterFrameHandler, so that it looks like this.

function enterFrameHandler (e:Event):void { //In each frame, add the necessary "forces" that moves the "gameBall" speedY += gravity; speedY += ay; speedX += ax; gameBall.y += speedY; gameBall.x += speedX; //Let's check when the ball hits the bottom. if (gameBall.y + radius > stage.stageHeight) { //When we hit the bottom, reposition the ball to be exactly on the //bottom edge. Change the sign of the speedY so we go to the other direction. gameBall.y = stage.stageHeight - radius; speedY *= -1; } }

Easy, eh? I think we still have two issues to fix, the side boundaries and the friction.  8. To decrease the speed in each frame, we use the friction variable. Change the enterFrameHandler to the following

function enterFrameHandler (e:Event):void { //In each frame, add the necessary "forces" that moves the "gameBall" speedY += gravity; speedY += ay; speedX += ax; forever

//Decrease the speed in each frame, so the ball won't bounce speedY *= friction; speedX *= friction; gameBall.y += speedY; gameBall.x += speedX;

//Let's check when the ball hits the bottom. if (gameBall.y + radius > stage.stageHeight) { //When we hit the bottom, reposition the ball to be exactly on the //bottom edge. Change the sign of the speedY so we go to the other direction. gameBall.y = stage.stageHeight - radius; speedY *= -1; }

//Check if the ball hits the top else if (gameBall.y - radius < 0) { gameBall.y = radius; speedY *= -1; } //Check the right edge if (gameBall.x + radius > stage.stageWidth) { gameBall.x = stage.stageWidth - radius; speedX *= -1; } //Check the left edge else if (gameBall.x - radius < 0) { gameBall.x = radius; speedX *= -1; } }

That's the end of this tutorial. Play with this with different values to have your own "physical world". If you have any questions, don't hesitate to ask in  the forum. 

Space Rocket with Actionscript 3

In this tutorial, I will show you how to create a space rocket with a trail effect. All the animation is done via Actionscript 3 of course!

Setting up the environment 1. Create a new document of size 400x400.  2. Draw a space rocket that points to the right. Don't pay attention to how it looks, since this is not a tutorial on drawing. Just draw something that you  might imagine to be a rocket.  3. Convert your rocket into a movie clip. Set the registration point to the center. Name it however you want.  4. Give the rocket an instance name of "rocket". 

Moving into Actionscript  5. Create an actions layer and type the following. 

//These variables tell us which button is down var leftArrow:Boolean = false; var rightArrow:Boolean = false; var upArrow:Boolean = false; //rotationSpeed defines how fast the rocket rotates var rotationSpeed:Number = 10;

//accelaration defines how fast we accelerate the ship var acceleration:Number = 0.5; //Ship x and y speed var xSpeed:Number = 0; var ySpeed:Number = 0; //Add ENTER_FRAME that moves the ship addEventListener (Event.ENTER_FRAME,moveRocket); //Listen for the key presses stage.addEventListener (KeyboardEvent.KEY_DOWN,keyDownHandler); stage.addEventListener (KeyboardEvent.KEY_UP,keyUpHandler); function moveRocket (e:Event):void { //First we rotate the ship if(rightArrow) { rocket.rotation += rotationSpeed; } if(leftArrow) { rocket.rotation -= rotationSpeed; } //If the user presses the up arrow, the following gets executed if(upArrow) { //Increase the x and y speeds xSpeed += Math.cos(Math.PI*rocket.rotation/180)*acceleration; ySpeed += Math.sin(Math.PI*rocket.rotation/180)*acceleration; //Create a fire when we acce var fire:MovieClip = new MovieClip(); //Draw the fire drawFire(fire); //Create a new fire at the end of the rocket fire.x = rocket.x Math.cos(Math.PI*rocket.rotation/180) * (rocket.width / 2); fire.y = rocket.y Math.sin(Math.PI*rocket.rotation/180) * (rocket.height / 2); //Add the fire to the stage addChildAt(fire,0); fire.addEventListener(Event.ENTER_FRAME, animateFire); } //Assign the new x and y position for the rocket rocket.x += xSpeed; rocket.y += ySpeed;

//Make the rocket appear on the other side if it's out of bounds if (rocket.x > stage.stageWidth) { rocket.x = 0; } else if (rocket.x < 0) { rocket.x = stage.stageWidth; } if (rocket.y > stage.stageHeight) { rocket.y = 0; } if (rocket.y < 0) { rocket.y = stage.stageHeight; } } //This is called when a user presses a key function keyDownHandler (e:KeyboardEvent):void { //Left arrow clicked if (e.keyCode == 37) { leftArrow = true; } //Right arrow clicked else if (e.keyCode == 39) { rightArrow = true; } //Up arrow clicked else if (e.keyCode == 38) { upArrow = true; } } //This is called when a user releases a key function keyUpHandler (e:KeyboardEvent):void { //Left arrow up if (e.keyCode == 37) { leftArrow = false; } //Right arrow up else if (e.keyCode == 39) { rightArrow = false; }

}

//Up arrow up else if (e.keyCode == 38) { upArrow = false; }

//This funtion draws a red ball function drawFire (mc:MovieClip):void {

//Give a random color for the circle mc.graphics.beginFill (0xff0000); //Draw the cirlce mc.graphics.drawCircle (0, 0, 10);

}

//End the filling mc.graphics.endFill ();

//This function fades the fire in each frame function animateFire(e:Event):void { ball.

//In each frame, reduce the alpha and the scale of the trail e.target.alpha -= 0.04; e.target.scaleY -= 0.04; e.target.scaleX -= 0.04;

//Remove the fire if the alpha is less than zero if(e.target.alpha<0) { e.target.removeEventListener(Event.ENTER_FRAME, animateFire); removeChild((MovieClip)(e.target)); } }

You are done, test your movie! I hope you enjoyed this tutorial and learned something from it. If you have any questions concerning this tutorial, please  visit the forum. 

Zoom Website via Actionscript 3

In this tutorial, I'll show you how to create a one frame website using Actionscript 3. You can see the end result in the movie above. 

Setting up the environment 1. Create a new document of size 300x300.  2. Draw three different colored rectangles. Make them 100x100.  3. Type some text on them, eg. "page 1", "page 2" and "page 3".  4. Convert each rectangle into a movie clip. You can name them however you want, just set the registration points to the center!  5. Position the rectangles as in the image below.

6. Give the rectangles instance names, "page01", "page02" and "page03". 

Moving into Actionscript First, don't get scared of the amount of code! It's really straight forward, if you bother to read the comments as well. 7. Create a new layer for actionscript. Type the following in the first frame. 

import fl.transitions.Tween; import fl.transitions.easing.*; import fl.transitions.TweenEvent; //Store the current page that is displayed var currentPage:MovieClip = null; //This array holds all the tweens so they won't get //carbage collected var tweens:Array = new Array();

//Make the buttons 50% transparent page01.alpha = 0.5; page02.alpha = 0.5; page03.alpha = 0.5; //Make the pages look like button (hand cursor) page01.buttonMode = true; page02.buttonMode = true; page03.buttonMode = true; //Add all the necessary event listeners addEventListeners(); //This function adds the necessary event listeners for the buttons function addEventListeners():void { //Add mouse over handlers for each button page01.addEventListener(MouseEvent.MOUSE_OVER, mouseOverHandler); page02.addEventListener(MouseEvent.MOUSE_OVER, mouseOverHandler); page03.addEventListener(MouseEvent.MOUSE_OVER, mouseOverHandler); //Add mouse out handlers for each button page01.addEventListener(MouseEvent.MOUSE_OUT, mouseOutHandler); page02.addEventListener(MouseEvent.MOUSE_OUT, mouseOutHandler); page03.addEventListener(MouseEvent.MOUSE_OUT, mouseOutHandler); //Add mouse click handlers for each button page01.addEventListener(MouseEvent.CLICK, mouseClickHandler); page02.addEventListener(MouseEvent.CLICK, mouseClickHandler); page03.addEventListener(MouseEvent.CLICK, mouseClickHandler); } //This function removes all the event listeners created //in the addEventListeners() function function removeEventListeners():void { //Add mouse over handlers for each button page01.removeEventListener(MouseEvent.MOUSE_OVER, mouseOverHandler); page02.removeEventListener(MouseEvent.MOUSE_OVER, mouseOverHandler); page03.removeEventListener(MouseEvent.MOUSE_OVER, mouseOverHandler); //Add mouse out handlers for each button page01.removeEventListener(MouseEvent.MOUSE_OUT, mouseOutHandler); page02.removeEventListener(MouseEvent.MOUSE_OUT, mouseOutHandler); page03.removeEventListener(MouseEvent.MOUSE_OUT, mouseOutHandler); //Add mouse click handlers for each button

page01.removeEventListener(MouseEvent.CLICK, mouseClickHandler); page02.removeEventListener(MouseEvent.CLICK, mouseClickHandler); page03.removeEventListener(MouseEvent.CLICK, mouseClickHandler); } //This is called when the mouse is over the button function mouseOverHandler(e:MouseEvent):void { //Get the button from the event var button:MovieClip = e.target as MovieClip; //Fully opaque button.alpha = 1; } //This is called when the mouse moves away from the button function mouseOutHandler(e:MouseEvent):void { //Get the button from the event var button:MovieClip = e.target as MovieClip; //50% transparent button.alpha = 0.5; } //This is called when the mouse is clicked on a button function mouseClickHandler(e:MouseEvent):void { //Remove the event listeners while we animate removeEventListeners(); //Get the button from the event var button:MovieClip = e.target as MovieClip; //Clicked button is now our current page currentPage = button; //Make the current page fully opaque currentPage.alpha = 1; //Add the current page to the top of the stage setChildIndex(currentPage, 2); //Animate the button to the center of the stage var tweenX:Tween = new Tween(currentPage, "x", Regular.easeOut, currentPage.x, 150, 0.5, true); //Push the tween to an array tweens.push(tweenX); //Listen when the tween is finished tweenX.addEventListener(TweenEvent.MOTION_FINISH, centerTweenFinished); } //This is called when the page is moved to the center of the stage

function centerTweenFinished(e:TweenEvent):void { //Grow the page to almost full screen size var tweenX:Tween = new Tween(currentPage, "scaleX", Regular.easeOut, 1, 2.5, 1, true); var tweenY :Tween = new Tween(currentPage, "scaleY", Regular.easeOut, 1, 2.5, 1, true); //Add the tweens to the array tweens.push(tweenX); tweens.push(tweenY); //Add a click listener for closing the current page currentPage.addEventListener(MouseEvent.CLICK, currentPageClicked); } //This function is called when the current page is clicked function currentPageClicked(e:Event):void { //Scale the current page down var tweenX:Tween = new Tween(currentPage, "scaleX", Regular.easeOut, 2.5, 1, 1, true); var tweenY:Tween = new Tween(currentPage, "scaleY", Regular.easeOut, 2.5, 1, 1, true); //Push the tweens to an array tweens.push(tweenX); tweens.push(tweenY); //Listen when the scaling down is finished tweenX.addEventListener(TweenEvent.MOTION_FINISH, scaleDownFinished); //Remove the click listener for the current page currentPage.removeEventListener(MouseEvent.CLICK, currentPageClicked); } //This function is called when scaling the current page down //is finished function scaleDownFinished(e:Event):void { var tweenX:Tween; //Move the current page to the original position if (currentPage == page01) { tweenX = new Tween(currentPage, "x", Regular.easeOut, currentPage.x, 50, 0.5, true); } else if (currentPage == page02) { tweenX = new Tween(currentPage, "x", Regular.easeOut,

currentPage.x, 150, 0.5, true); } else { tweenX = new Tween(currentPage, "x", Regular.easeOut, currentPage.x, 250, 0.5, true); } //Push the tween to an array tweens.push(tweenX); //Add all the event listeners back addEventListeners(); }

You are done, test your new Flash movie! If you have any questions, please visit the forum.

Actionscript 3 Dragging Methods This tutorial is all about dragging an object around the stage. You will learn different ways to implement dragging. I'll also show you how to add some  animation with the dragging. So start your Flash IDE and let's get going! 

Actionscript 3 startDrag and stopDrag methods The methods startDrag and stopDrag are probably the most easiest methods to implement dragging. Follow these steps and see yourself!  1. Create a new document of size 400x400.  2. Draw a ball of size 80x80 to the center of the stage.  3. Convert the ball into a movie clip called "ball".  4. Create a layer for actionscript and type the following.

//Add event listeners for the MOUSE_DOWN and MOUSE_UP //events, so we know when to start/stop dragging. ball.addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler); ball.addEventListener(MouseEvent.MOUSE_UP, mouseReleasedHandler); //This function is called when the user presses the mouse on the ball function mouseDownHandler(e:MouseEvent):void { ball.startDrag(); } //This function is called when the user releases the mouse function mouseReleasedHandler(e:MouseEvent):void { ball.stopDrag(); }

Now test your movie. You now have a draggable object on the stage! 

NOTE: If you want to snap the center of the ball to the mouse position when dragging, replace the mouseDownHandler with the following. 

//This function is called when the user presses the mouse on the ball function mouseDownHandler(e:MouseEvent):void { ball.startDrag(true); }

That's the basics of actionscript 3 dragging. As you see, the dragging effect looks quite boring. Why not add some animation to it?

Actionscript 3 dragging with simple movement The next piece of code moves the circle to the cursor's coordinates in a constant speed when dragging. Erase the old actionscript code and type the  following.

//This variable tells whether the user is dragging or not var dragging:Boolean = false; //x and y speeds var speedX:Number = 0; var speedY:Number = 0; //Overall speed var speed:Number = 10; //Add event listeners for the MOUSE_DOWN and MOUSE_UP //events, so we know when to start/stop dragging. ball.addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler); stage.addEventListener(MouseEvent.MOUSE_UP, mouseReleasedHandler); //Add ENTER_FRAME which animates the ball movement addEventListener(Event.ENTER_FRAME, moveBall);

//This function is called when the user presses the mouse on the ball function mouseDownHandler(e:MouseEvent):void { dragging = true; } //This function is called when the user releases the mouse function mouseReleasedHandler(e:MouseEvent):void { dragging = false; } function moveBall(event:Event):void { //We only move the ball when the user is dragging if (dragging) { //Calculate the x and y distances from the ball to the

mouse

var distanceX:Number = mouseX - ball.x; var distanceY:Number = mouseY - ball.y; //Calculate the distance from the mouse to the ball var dist = Math.sqrt(distanceX*distanceX + distanceY*distanceY);

distanceX);

//If the distance is larger than 5, we move the ball if (dist > 5) { //Calculate the angle from the ball to the mouse var angle:Number = Math.atan2(distanceY, //Calculate the new x and y speeds speedX = Math.cos(angle) * speed; speedY = Math.sin(angle) * speed; //Move the ball to the new coordinates (closer to

the mouse) } }

ball.x += speedX; ball.y += speedY;

}

Test your movie and you should have the same animation as seen below. 

Dragging with spring  The next piece of code applies a spring effect to the dragging. Erase the old actionscript code and type the following. 

//This variable tells whether the user is dragging or not var dragging:Boolean = false; //Spring variable (how strong the spring effect is) var springFactor:Number = 0.2; //Friction for the animatiom var friction:Number = 0.9; //x and y speeds var speedX:Number = 0; var speedY:Number = 0; //acceleration for x and y speeds var accX:Number = 0; var accY:Number = 0; //Overall speed var speed:Number = 10; //Add event listeners for the MOUSE_DOWN and MOUSE_UP //events, so we know when to start/stop dragging. ball.addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler); stage.addEventListener(MouseEvent.MOUSE_UP, mouseReleasedHandler); //Add ENTER_FRAME which animates the ball movement addEventListener(Event.ENTER_FRAME, moveBall);

//This function is called when the user presses the mouse on the ball function mouseDownHandler(e:MouseEvent):void { dragging = true; } //This function is called when the user releases the mouse function mouseReleasedHandler(e:MouseEvent):void { dragging = false; } function moveBall(event:Event):void { //We only move the ball when the user is dragging if (dragging) { //Calculate the x and y distances from the ball to the mouse

var distanceX:Number = mouseX - ball.x; var distanceY:Number = mouseY - ball.y; //Update x and y accelerations accX = distanceX * springFactor; accY = distanceY * springFactor; //Add the acceleration to the speed speedX += accX; speedY += accY; //Add friction, otherwise the animation //would go on forever. speedX *= friction; speedY *= friction; //Move the ball to the new coordinates (closer to the

mouse) } }

Test your movie! 

ball.x += speedX; ball.y += speedY;

Things are looking much more interesting now, don't you think? In the next page, I'll show you how to add a trail effect for the spring dragging. 

Dragging with trail effect In the last part of this tutorial, I will teach you how to create a trail effect while dragging an object. 

1. Linkage the ball movie clip to a class named "Ball". If you don't know how linkage a movie clip, check step 4 of the Actionscript 3 External Classes  tutorial. 

2. Add the following code in your actionscript code (don't erase the old one). 

//We use this timer to create a trail ball each 0.03 seconds var timer:Timer = new Timer(30,400000); timer.addEventListener(TimerEvent.TIMER, createTrailBall); timer.start(); //This function is called by the timer function createTrailBall(e:Event):void { //Create a new ball instance var trailBall:Ball=new Ball(); //Position the trail ball in the same position where the original ball is located trailBall.x = ball.x; trailBall.y = ball.y; //Add ENTER_FRAME to animate the trail ball trailBall.addEventListener(Event.ENTER_FRAME,animateTrailBall); /* Add the trail ball on to the stage. We don't want to position the trail ball on top of the original ball.

We use the addChildAt method to set the index to 0. */ addChildAt(trailBall,0);

} function animateTrailBall(e:Event):void { ball.

//In each frame, reduce the alpha and the scale of the trail e.target.alpha -= 0.1; e.target.scaleY -= 0.1; e.target.scaleX -= 0.1; /* If the alpha is less than 0, we remove the trail ball from the stage. */ if (e.target.alpha < 0) {

e.target.removeEventListener(Event.ENTER_FRAME,animateTrailBall); removeChild((MovieClip)(e.target)); } }

That's it for this tutorial. I hope you enjoyed it and learned something new! Remember, if you have any questions, post them in the forum.

Related Documents

Timer Class
November 2019 18
Timer 555
May 2020 10
Exam Timer
November 2019 23
86 Timer
May 2020 12
Msa Timer
April 2020 3
Ne555 Timer
June 2020 1