Friday, May 27, 2011

How to Make an Etch a Sketch in AS3



Difficulty: Easy


Skills Used: addChild, removeChild, depth, sound effects, arrays, for loops, event listeners, registration points, particles, key events


Make a working Etch a Sketch. Draw anything your little heart desires using your arrow keys, then erase it by hitting "Erase!"

Instructions:
1. Make a new file in Flash. Make sure it's Actionscript 3.0.  Right click on the grey area next to the stage and select "Document Properties". Set the stage to 480 x 360 pixels.

2. In the timeline, create five layers and name them (from top to bottom) "Actions", "Erase", "Knobs", "Frame", and "BG". Download the picture of the Etch a Sketch from the bottom of this tutorial, import it to your library, and place it in the "BG" layer. Center it so it covers the entire stage.

3. We want the Etch a Sketch "drawing" to appear to be under the red frame, not on top of it. Download the frame from the bottom of this tutorial (download it, don't just copy and paste or you'll have a white background) and import it to your library. Drag it into the "Frame" layer and center it so it is directly above the background picture.

4. Even though we're not really using the knobs on this Etch a Sketch, it's still fun to make them turn. Download the picture of the knob (download it, if you copy and paste you'll get a white background) and import it into your library. Drag the knob into your "Knob" layer and place it directly over the left knob on the Etch a Sketch frame. (X: 45, Y: 324.5) Right click the knob and select "Convert to Symbol". It doesn't matter what you name the movieclip, just call it "knob". But in the properties inspector, give the instance of the knob the name "leftKnob". I rotated my left knob 90 degrees clockwise to make it look a little different from the right knob.

5. Drag a second instance of your knob movieclip into the "Knobs" layer and place it directly over the right knob on the Etch a Sketch frame. (X: 442.5, Y: 325) In the properties inspector, name this second instance "rightKnob".

6. In the top menu, select Insert -> New Symbol. Name the symbol "particle".Use the Oval Tool to make a circle that is .75 x .75, with no stroke, and fill it with 555555. Use the align menu to center it over the registration point. (The registration point is that little cross in the center of the screen.) Go to the library. Find the particle movie clip. Double click to the right of "particle", under the "Linkage" column, and type in "particle". So now it should say "particle" under "Name" and under "Linkage".

7. Go back to the mainframe of the movie by clicking "Scene 1" in the upper left corner. Select the "Actions" layer in the timeline. Open the Actions window and paste in the following code...

import flash.display.Sprite;
import flash.events.KeyboardEvent;/*Important! Otherwise when you post your swf to the web the keys won't register.*/

var Xloc:uint = 63;/*where the particles will be drawn on the stage*/
var Yloc:uint = 61;/*where the particles will be drawn on the stage*/
var particleArray:Array = new Array();/*an array to keep the particles organized*/

stage.addEventListener(KeyboardEvent.KEY_DOWN, sketch);/*when the user presses a key, call the sketch function*/
function sketch(event:KeyboardEvent):void
{
switch (event.keyCode)
{
case 37:
//left
if (Xloc > 58)
{
Xloc -= 1;//adjust the left/right position
leftKnob.rotation -= 5;/*rotate the knob*/
}
break;
case 39:
//right
if (Xloc < 425)
{
Xloc += 1;
leftKnob.rotation += 5;
}
break;
case 38:
//up
if (Yloc > 56)
{
Yloc -= 1;
rightKnob.rotation -= 5;
}
break;
case 40:
//down
if (Yloc < 299)
{
Yloc += 1;
rightKnob.rotation += 5;
}
break;
default:
trace (event.keyCode)/*this is a good way to look up the keycode for a key you don't know*/
}

/*draw a particle on the screen*/
var particleMC = new particle();
particleMC.x = Xloc;
particleMC.y = Yloc;
addChildAt(particleMC,1);/*we're drawing the particles at depth 1, which is above the background but below everything else*/
particleArray.push(particleMC);/*adds drawn particles to an array, will make it easy to erase them later*/
}

This creates an event listener that waits for the user to press a key. Every time the user presses an arrow key, it moves the location where a particle will be drawn either left, right, up, or down. Then it draws the particle, and adds it to an array to keep things organized. Notice that I'm using "addChildAt" instead of "addChild". This draws the particles at depth 1, just above the background layer, so it won't appear on top of the frame.

Test your movie. You should be able to draw on your Etch a Sketch using the arrow keys, and the knobs should turn.

8. The app is almost finished, but there's no way to erase your drawing. We need to fix that. Download the Erase button from the bottom of the tutorial. (Download it, don't just copy and paste.) Import it to your library, drag it to the "Erase" layer, and use the properties inspector to move it to X: 177, Y: 301. Right click the button and select "Convert to Symbol". Name the movieclip "erase", or whatever you want, doesn't really matter. Then in the properties inspector name this instance of the movieclip "erase".

9. (Optional) Find or record a sound effect for "shaking" the Etch a Sketch. I recorded myself gently shaking some rice in a plastic bag using Audacity. Import it to your library. Double click next to your mp3 file, under "Linkage" and name it "shake".

10. Select the "Actions" layer and open the actions window again. Add the following code to the bottom of the window:

erase.addEventListener(MouseEvent.CLICK, eraseParticles);/*when you click the erase button, it calls the eraseParticles function*/

var shakeEffect:Sound = new Sound();
shakeEffect = new shake();
var shakeChannel:SoundChannel = new SoundChannel();/*get the shake sound ready*/

function eraseParticles(event:MouseEvent):void
{
shakeChannel = shakeEffect.play();/*play shake sound effect*/

for (var i:uint=particleArray.length-1; i>0; i--)/*kind of backwards, but this way I can use the pop method*/
{
removeChild(particleArray[i]);/*removes particle from stage*/
particleArray.pop();/*removes last item from array*/
}
}

This puts an event listener on the erase button so when the user clicks it, it calls the eraseParticles function. The function plays the sound effect and uses a backwards forloop to erase each particle one by one and delete it from the array. If you're not using a sound effect, erase or comment out the four lines that contain the word "shake".

You're done! Test your movie and make sure it's drawing and erasing properly.

Final Code:


import flash.display.Sprite;
import flash.events.KeyboardEvent;/*Important! Otherwise when you post your swf to the web the keys won't register.*/

var Xloc:uint = 63;/*where the particles will be drawn on the stage*/
var Yloc:uint = 61;/*where the particles will be drawn on the stage*/
var particleArray:Array = new Array();/*an array to keep the particles organized*/

stage.addEventListener(KeyboardEvent.KEY_DOWN, sketch);/*when the user presses a key, call the sketch function*/
function sketch(event:KeyboardEvent):void
{
switch (event.keyCode)
{
case 37:
//left
if (Xloc > 58)
{
Xloc -= 1;//adjust the left/right position
leftKnob.rotation -= 5;/*rotate the knob*/
}
break;
case 39:
//right
if (Xloc < 425)
{
Xloc += 1;
leftKnob.rotation += 5;
}
break;
case 38:
//up
if (Yloc > 56)
{
Yloc -= 1;
rightKnob.rotation -= 5;
}
break;
case 40:
//down
if (Yloc < 299)
{
Yloc += 1;
rightKnob.rotation += 5;
}
break;
default:
trace (event.keyCode)/*this is a good way to look up the keycode for a key you don't know*/
}

/*draw a particle on the screen*/
var particleMC = new particle();
particleMC.x = Xloc;
particleMC.y = Yloc;
addChildAt(particleMC,1);/*we're drawing the particles at depth 1, which is above the background but below everything else*/
particleArray.push(particleMC);/*adds drawn particles to an array, will make it easy to erase them later*/
}

erase.addEventListener(MouseEvent.CLICK, eraseParticles);/*when you click the erase button, it calls the eraseParticles function*/

var shakeEffect:Sound = new Sound();
shakeEffect = new shake();
var shakeChannel:SoundChannel = new SoundChannel();/*get the shake sound ready*/

function eraseParticles(event:MouseEvent):void
{
shakeChannel = shakeEffect.play();/*play shake sound effect*/

for (var i:uint=particleArray.length-1; i>0; i--)/*kind of backwards, but this way I can use the pop method*/
{
removeChild(particleArray[i]);/*removes particle from stage*/
particleArray.pop();/*removes last item from array*/
}
}


Download the Image Files:







Thursday, May 26, 2011

How to Make an Arrow Point at the Mouse in AS3


Difficulty: Easy


Skills Used: trigonometry, mouse location, dynamic textboxes

A simple movie clip where the rotation of the arrow is based on the mouse's location. Good introduction to using trigonometry in Actionscript 3.0.

Instructions:
1. Open up a new file in Flash. Make sure you are using Actionscript 3.0. I made my stage 300x300 pixels.

2. In the top menu, select Insert -> New Symbol. Name the symbol "arrow". Draw an arrow pointing straight up. Then drag the arrow so that it's registration point (that's the little cross that always stays in place no matter where you put the arrow) is at bottom center of your arrow. The registration point determines how the arrow will rotate, so this is important.

3. In the upperleft corner where it says "Scene 1 arrow" click on "Scene 1". This brings you back to the mainframe of the movie. Drag the arrow symbol from the library to the stage, center it and keep it close to the top of the stage. Rename the current layer in the timeline "arrow".

4. Create a new layer in the timeline and name it "Actions". Open up the actions window and paste the following code:

addEventListener(Event.ENTER_FRAME, rotate);

function rotate(e:Event)
{
var x:int = mouseX - myArrow.x;
var y:int = mouseY - myArrow.y;

var angle:int = Math.atan(y/x)/(Math.PI/180); //finds the arc tan of x/y, then converts it to degrees

if (x<0)
{
angle += 180;
}

myArrow.rotation = angle + 90;
}

This creates an event which will update the arrow's location every time the movie enters a new frame. It calculates the arctan of y/x, then converts that number from radians to degrees. Arctan is always positive, which means if we didn't modify the angle it would always point to the right. The if statement determines if the arrow should be pointing to the right. Finally, we add 90 degrees to the angle calculated because otherwise the arrow would be at an angle to the mouse.

Test your movie, the arrow should be pointing to the mouse at all times.

5. (Optional) If you want to see the degree of the angle of your arrow, which could help you modify the code later on, then you can add a dynamic text box that shows the current angle. Create a new layer in the timeline called "text". Use the text tool to draw a text field box on the stage. Center the textfield.

In the properties inspector, name the instance of this textbox "myAngle". Make sure it is set to "classic text", not "TLF" text. Make sure it is "dynamic", not "static" or "input". In the "Character" menu, click the button that says "Embed.." and a menu will pop up. In the "Character ranges" list, select "Numerals 0-9", then hit OK. (It's important to always embed your text, otherwise the text could disappear at inconvenient times.) Back in the properties inspector, under the "Paragraph" menu, set the format to centered.

Select the "Actions" layer and open up the Actions window again. Inside of the "rotate" function, add one last line of code:

myAngle.text = String(myArrow.rotation);

You're done! Test your movie and make sure the textbox is displaying the angle correctly.


Final Code:

addEventListener(Event.ENTER_FRAME, rotate);

function rotate(e:Event)
{
var x:int = mouseX - myArrow.x;
var y:int = mouseY - myArrow.y;

var angle:int = Math.atan(y/x)/(Math.PI/180); //finds the arc tan of x/y, then converts it to degrees

if (x<0)
{
angle += 180;
}

myArrow.rotation = angle + 90;

myAngle.text = String(myArrow.rotation);
}

How to Make a Scrolling Menu in AS3



Difficulty: Medium


Skills Used: tweens, buttons, links


Instructions:
1. Get your posters (or whatever you'd like to display) together. Open them up in Photoshop and make thumbnails of each one. In my menu the vertical posters are about 200 px tall, and the horizontal posters are about 150 px tall.

2. As long as you're in Photoshop, let's go ahead and make the buttons that you will need. If you'd rather, you can download mine at the bottom of this tutorial. (Note: These are pngs, so download them, don't just copy and paste them, or you will get backgrounds.) Create a new layer, delete the background layer (so you can see the grey and white grid), then make your button. I made mine a circle with an arrow-shaped hole cut out of it, and I added shading and drop shadows. The circle is about 100 x 100. Save your button as a png. Remember, you can just make one and then flip it horizontally.

Don't know how to use Photoshop? There's an ebook that can teach you in just a few hours. Check it out here.

3. Open up a new Flash document. Make sure you're using Actionscript 3.0. My stage is 600 x 300, and I made the background color 333333. You'll have to decide what's best for your website and your posters. Import your arrows and poster thumbnails into the library.

4. From the menu at the top, select Insert -> New Symbol. Name your new symbol "posters", or something you'll remember. In the timeline, create a layer, name it "posterThumbnails". Drag the symbol posters into the layer posters, then use the align menu to center it. (I know, it's just a little circle, just center that circle.)

5. Double click on the little circle that represents your posters movieclip so that at the top of the stage, where it said "Scene 1", now it should say "Scene 1 posterThumbnails". Create a layer in the timeline and name it "thumbnails". Start dragging your thumbnails to the stage. Make sure they all have the same Y value in the properties inspector and look evenly spaced. When you run out of room, select all the posters and slide them over. You can quickly select all of the posters at once by clicking on the "thumbnails" layer you created. The length of your thumbnails should be significantly wider than the stage, otherwise what would be the point of scrolling? When you're done, position the thumbnails so that the leftmost poster is close to the left edge of the stage.

6. Go through the thumbnails (know, it's very tedious) and convert each one to a movieclip by right clicking the thumbnail and choosing "Convert to Symbol". Then name the instance on the stage a name that will be easy to remember.

7. Create another layer and name it "Actions". Open up the Actions Window and for each poster thumbnail, you will need to add the following code:

posterName.addEventListener(MouseEvent.CLICK, clickPosterName);

function clickPosterName(evt:MouseEvent):void
{
navigateToURL(new URLRequest("http://yourPostersURL.com"), "_same");
}

The "poster name" is the name you gave to the instance of the thumbnail in step 6. The URL should be a website that displays the poster or whatever is related to it.

Test your movie. Make sure the proper website opens up when you click on each thumbnail.

8. Go back to the main frame by clicking on "Scene 1" above the stage. Create a layer on the timeline (above the thumbnails layer) called "buttons". Place the left and right buttons in this layer. In the properties inspector, name the instance of the left button "leftButton" and the instance of the right button "rightButton".

9. Select the thumbnails layer. You need to decide how far the thumbnails should move to the right and left before they automatically stop. Drag it to the left as far as you want it to go. Look at the properties inspector and write down the X position. Now drag the thumbnails layer to the right as far as you want it to go. Look at the properties inspector again and write down the X position again. Then put the thumbnails layer back where you want it to be when the menu first opens up.

10.  Create another layer in the timeline. Name this one "Actions". (Yes, you made an actions layer before, but that was within the thumbnails movieclip, remember?) Open up the actions window and paste in the following code...

import fl.transitions.*;
import fl.transitions.easing.*;

var leftTween:Tween;
var rightTween:Tween;

rightButton.addEventListener(MouseEvent.CLICK, goRight);
leftButton.addEventListener(MouseEvent.CLICK, goLeft);

function goRight(evt:MouseEvent):void
{
if (thumbnails.x > -700)
{
leftTween = new Tween(thumbnails,"x",Strong.easeOut, thumbnails.x, (thumbnails.x - 200),2,true);
}
}

function goLeft(evt:MouseEvent):void
{
if (thumbnails.x < 2350)
{
rightTween = new Tween(thumbnails,"x",Strong.easeOut, thumbnails.x,(thumbnails.x + 200),2,true);
}
}

Both of the functions begin with an if statement. Change the "-700" and the "2350" to the x values you wrote down in step 9. The smaller number should go in the "goRight" function, the larger number should go in the "goLeft" function.


10. Test your movie. Do the buttons work? Are you happy with how far the thumbnails scroll? Do the thumbnails automatically stop when you go too far to the right or left? If your thumbnails aren't scrolling, make sure that you named the instances properly. The thumbnails should be called "thumbnails", the left button should be called "leftButton" and the right button should be called "rightButton".


11. Make another layer in the timeline, below the "buttons" layer. Call it "fadeout". This is where you will place your gradient rectangles, so your posters fade away instead of just falling off the stage. Download my gradient from the bottom of this tutorial if you need an example. Open it up in Photoshop. Mine is 100 pixels wide, about 1/6 of of the width of the stage, and 300 pixels tall, the same height as the stage. If you need to make your own, just open up a new file that's the size you need. Create a new layer. Delete the background layer. In layer 1, use the gradient tool to make a gradient that starts out the same color as the background of your movie and ends up transparent. Save it as a png. Then flip it horizontally and save it again.

12. Go back to Flash. Import your two gradients to the library, then drag them to the "fadeout" layer. Place the left one so it is centered vertically and hangs just to the left of the left side of the stage. Place the right one so it is centered vertically and ends just to the right of the right edge of the stage. Test your movie one more time and make sure you can't see a gap on the edges of your movie.

You're done!


Download the Image Files:



Tuesday, May 24, 2011

How to Animate a Magnet and Paperclip in AS3




Difficulty: Easy


Skills Used: follow the mouse, follow the mouse with delay, event listeners, rotation, registration points


Instructions:
1. Create a picture of a magnet and a paperclip. I made mine directly in Flash. If you'd like, you can download my magnet and paperclip at the bottom of this tutorial.

To Create the Pictures in Flash
Click on "Insert" in the menu at the top of the page, and select "New Symbol" from the dropdown menu. Give the symbol a name you will remember. Draw your magnet using the tools.

To Create the Pictures in Photoshop
Download my images from the bottom of this tutorial and open them in photoshop. Use the wand tool to select the background, then hit delete. If the background is transparent, you should be able to see that white and gray grid. Delete the background layer if necessary. Save the file as a png. Import the png to your library. You will need to convert the png to a movie clip by right-clicking on the png and selecting "Convert to Symbol" from the dropdown menu.

Don't know how to use Photoshop? You can learn it in just two hours! Click here to get the tutorial.

2. Create three layers and name them "Actions", "Paperclip", and "Magnet" respectively. Drag the paperclip into the "Paperclip" layer, convert to a symbol if necessary. In the properties inspector, name this instance "paperclip". Drag the magnet into the "Magnet" layer, convert to a symbol if necessary.  In the properties inspector, name this instance "magnet".

3. In the library, double-click the paperclip. See that little cross that always stays in the same place no matter where you move the paperclip? That's the registration point. It serves as the rotation point of the paperclip, and also determines where it will be positioned in respect to the mouse. Drag the paperclip so that the registration point is at the top center.

In the library, double-click the magnet. Set the registration point. I set it to the left leg of the magnet. This will determine where the paperclip will "stick" to the magnet.

4. Select the "Actions" layer in the timeline and open the Actions window. Add the following code:

addEventListener(Event.ENTER_FRAME, moveStuff);

function moveStuff(e:Event)
{
/*paper clip follows the mouse with delay*/
paperclip.x += (mouseX - paperclip.x)/6;
paperclip.y += (mouseY - paperclip.y)/6;

/*move the magnet*/
magnet.x = mouseX;
      magnet.y = mouseY;
}

The event listener tells the function "moveStuff" to run every time the movie enters a new frame. The function tells the magnet to follow the mouse and the paperclip to follow the mouse with a delay. To make the magnet "stronger", change the "6" to a smaller number. To make the magnet "weaker", change the "6" to a larger number.

Run your movie. Make sure the magnet is following the mouse and the paperclip is trailing behind the mouse.

5. The paperclip is gliding across the stage without rotating at all. We will add code to control the rotation of the paperclip so that it is always "pointing" at the mouse. In the Actions window, add the following code inside of the "moveStuff" function.

/*control the angle of the paperclip*/
var myAngle = Math.atan( (paperclip.x - magnet.x) / (paperclip.y - magnet.y) )
paperclip.rotation = myAngle/(Math.PI/180);

"myAngle" uses the arctan function to determine the angle of the paperclip based on the difference between the mouse's location and the paperclip's location. The rotation of the paperclip is them set to myAngle/(Math.PI/180) because "myAngle" is in radians and we need to convert it to degrees.

Test your movie again. The paperclip should skitter in a more realistic way now.

6. We're almost done, but the mouse is still visible. Well add more code to hide it. At the top of the Actions window, add the following code: (If you don't, the movie might look like it's working, but post it to the web and the mouse will be visible again.)

import flash.ui.Mouse;
Mouse.hide();

Then, at the bottom of the Actions window, add these two functions:

stage.addEventListener(Event.MOUSE_LEAVE, showMouse);

function showMouse(evt:Event):void
{
Mouse.show();
}

stage.addEventListener(MouseEvent.MOUSE_MOVE, hideMouse);

function hideMouse(evt:Event):void
{
Mouse.hide();
}


The first function shows the mouse every time it leaves the stage. The second function hides the mouse every time it moves within the stage.

7. (Optional) I tried to make it look like the magnet and the paperclip are on opposite sides of a glass panel. If you'd like, create a nearly transparent glass layer in photoshop (with no background!), save it as a png, then import it to the library and drag it onto the stage in a layer between the magnet and paperclip.

You're done! Think of something else you can make that follows the mouse with a delay.

Final Code:

import flash.ui.Mouse;
Mouse.hide();/*You must include this or the mouse will be visible when you post your movie to the web!*/

addEventListener(Event.ENTER_FRAME, moveStuff);

function moveStuff(e:Event)
{
/*paper clip follows the mouse with delay*/
paperclip.x += (mouseX - paperclip.x)/6;
paperclip.y += (mouseY - paperclip.y)/6;

/*move the magnet*/
magnet.x = mouseX;
    magnet.y = mouseY;

/*control the angle of the paperclip*/
var myAngle = Math.atan( (paperclip.x - magnet.x) / (paperclip.y - magnet.y) )
paperclip.rotation = myAngle/(Math.PI/180);
}

/*if the mouse leaves the map, show the mouse*/
stage.addEventListener(Event.MOUSE_LEAVE, showMouse);

function showMouse(evt:Event):void
{
Mouse.show();
}

/*if the mouse moves anywhere on the stage, show the mouse*/
stage.addEventListener(MouseEvent.MOUSE_MOVE, hideMouse);

function hideMouse(evt:Event):void
{
Mouse.hide();
}

Download the Image Files:





How to Create a Magnifying Glass in AS3



Difficulty: Easy

Skills Used: following the mouse, Layer Masks, Event Listeners, registration points



This is a simple movie to make, but it can be used for lots of applications. A larger version of the map sits in a layer on top of the original. A layer mask hides the large map except for within the circle of the magnifying glass. The large map also moves back and forth according the movement of the mouse.


Instructions:
1. Find a large picture to use for your tutorial. (Remember, always start with a big picture and then make it smaller, don't start with a small picture and make it bigger.) It doesn't have to be a map, but for this tutorial we will assume it is. You can download the map of Riverside at the end of this tutorial if you would like.

2. Open the large map in Photoshop and create a smaller version. My magnifying glass magnifies things by 2.5, so to make my smaller picture, I divided the width and height of the large map by 2.5.

Original Map             Divide By            Small Map
Width: 936 px            /2.5                        = 374 px
Height: 1071 px         /2.5                        = 428 px


Don't know how to use Photoshop? You can learn it in just two hours! Click here to download the tutorial.


3. Open a new file in Flash. Make sure you choose Actionscript 3.0. Right click on the grey area around the stage and choose Document Properties from the menu that pops up. Set the stage width and height to that of your small picture, in my case 374 x 428.

4. Import your large and small map to the library. Create a layer in the timeline and call it "Small Map". Place the small map in that layer and center it so it covers the entire stage. Create a second layer and call it "Big Map". Drag the large map into that layer. (It does not have to be centered on the stage, as it will be positioned through AS3. You can put it to the side to make it easier to see the small map.)

5. In the Properties Inspector name the instance of your large map "myMap". Create a third layer in the timeline and name it "Actionscript". Open up the Actions window and add this code:


myMap.addEventListener(Event.ENTER_FRAME, magnify);

function magnify(e:Event)
{
     myMap.x = (mouseX * -1.5);
     myMap.y = (mouseY * -1.5);
}

The event listener means the movie will read this code every time it enters a new frame. The large map is 2.5 times as big as the small map, so for every one unit the mouse moves, the large map moves another 1.5 units. 1 + 1.5 = 2.5. Get it? Test your movie and make sure the large map is moving around properly.

6. Create another layer above "Big Map" and name it Glass. Use the oval tool to create a circle in this layer. Mine is 100 x 100. It doesn't matter what color the fill is, you won't be able to see it. However, you will see the color of the stroke. Mine is 996600. Hold down the shift key while you are creating the shape so you get a circle and not an oval.


7. Select the stroke around the circle, then choose Edit -> Cut. We will be pasting the rim of the circle in a separate layer.

8. Right click the circle and select "Convert to Symbol" from the pop up menu. Convert it to a movie clip, and name it "myCircle" or "magnifying glass", something you will recognize. In the properties inspector, name this instance "myCircle".

9. In the library, double click on the magnifying glass. Use the align tools (align horizontal center, align vertical center) to center the registration point. If you don't do this, the magnifying glass will be just below and to the right of the mouse.


10. Open up the Actions window again and add the following code to the function "magnify" that we created before.

myCircle.x = mouseX;
myCircle.y = mouseY;

Now the circle will always follow the mouse. Test your movie to make sure the circle is moving around properly.

11. Double check that the layer "Glass" is right above the layer "Big Map". Right click on the "Glass" layer and select "Mask" from the pop up menu. "Big Map" should now be under "Glass" and slightly indented. You have created a layer mask. Now you will only be able to see part of the big map that lies within the circle.

12. Create a layer above "Glass" called "Rim". Paste the stroke of the circle we cut earlier into the "Rim" layer. Right click the rim and convert it to a symbol. Call it "Rim" or whatever you'd like. In the properties inspector, name this instance of the rim "myRim". In the library, double click on the rim and use the align menu to center it over its registration point.

13. In the actions window, add the following code to the "magnify" event.

myRim.x = mouseX;
myRim.y = mouseY;

Test your movie and make sure the rim is centered over the glass and following your mouse.

14. Last step! You can still see the mouse in the center of the magnifying glass, and of course we don't want that. In the actions window, add the following code (I like to keep this at the top.)

import flash.events.Event;
import flash.events.MouseEvent;
import flash.ui.Mouse;

(This imports the information Flash needs to show and hide your mouse. If you don't add it, you might think your movie is working fine, but if you upload it to a website your mouse will be visible again.) Then add these two functions at the bottom of your code.

stage.addEventListener(Event.MOUSE_LEAVE, showMouse);

function showMouse(evt:Event):void
{
Mouse.show();
}

stage.addEventListener(MouseEvent.MOUSE_MOVE, hideMouse);

function hideMouse(evt:Event):void
{
Mouse.hide();
}

The first function allows the mouse to show whenever it leaves the stage. The second function hides the mouse whenever it moves within your movie.

You're done! Test your movie and make sure it works.

Final Code:
import flash.events.Event;
import flash.events.MouseEvent;
import flash.ui.Mouse; /*don't forget this part, otherwise the mouse will show if you post this to a website
*/

myMap.addEventListener(Event.ENTER_FRAME, moveBigMap);

function moveBigMap(e:Event)
{
/*the big map is 2.5 times bigger than the small map
for every one unit the mouse moves, the big map movies 1.5 units, 1 + 1.5 = 2.5*/
myMap.x = (mouseX * -1.5);
    myMap.y = (mouseY * -1.5);

/*move the magnifying glass*/
myCircle.x = mouseX;
    myCircle.y = mouseY;

/*move the rim of the magnifying glass*/
myRim.x = mouseX;
    myRim.y = mouseY;
}

/*if the mouse leaves the map, show the mouse*/
stage.addEventListener(Event.MOUSE_LEAVE, showMouse);

function showMouse(evt:Event):void
{
Mouse.show();
}

/*if the mouse moves anywhere on the stage, show the mouse*/
stage.addEventListener(MouseEvent.MOUSE_MOVE, hideMouse);

function hideMouse(evt:Event):void
{
Mouse.hide();
}




Download the Image Files