Flash Explained

Learn Flash easily.

Learning to create a scanning cursor that shows the mouse coordinates

October 15th, 2008 | Author: Luka | Category: Design


Ever seen this small piece of interface that can look really cool? A little crosshair-like cursor that shows the mouse coordinates in real-time? Or a similar design in sci-fi movies, like some cyborg’s targeting system, for example?

You’ll see in my tutorial that it is really, really easy to make. Move your mouse over the Flash example below to see an example of that.

Setting up the document's properties

1 Open a new Flash document. Before starting to design the crosshair cursor, you must set up your movie. Select Modify > Document and you'll open up the Document Properties window.

Set the width of your movie to 400 pixels and the height to 300. In the Frame rate field, enter 30. Click OK.

Adjusting the document properties.

The document's dimensions aren't important - you just don't need a bigger document for this lesson. However, the frame rate (the speed of your movie) is important for the custom cursor to move smoothly.

2 If you're working in Flash MX, skip this step. If not, select File > Publish Settings. Click the Flash tab on top of the dialog box that appears. Select Flash Player 6 as Version and ActionScript 1.0 as ActionScript version. Click OK.

This is done in order to ensure backward compatibility. Since there's very little (and simple) ActionScript involved, there isn't any reason not to do so.

3 Call the first layer custom cursor. You can do this by clicking on the layer's name (Layer 1) above the scene, entering the desired name and hitting Enter.

Top of page

Drawing the crosshairs cursor

4 Select the Rectangle tool (R). Block the fill color, because you'll be drawing an outline square.

Do this by going to the Colors portion of the Tools panel. Click on the small paint bucket icon (1 in the image below) to select the fill color. Next, click on the small square with the red diagonal line at the bottom of the panel (2). You just blocked the fill color.

Blocking out the fill colour.

5 In the Properties panel, below the scene, select hairline as type of line. Select any color you like.

The hairline option.

6 Hold Shift, click and start dragging. This will cause the creation of a square. If you release Shift, you will be drawing a rectangle. So, draw a square of any dimensions.

An outline square.

7 With the Selection tool (V), double-click on any one of the edges of the square to select the whole shape.

Selecting the square.

8 Go to the left side of the Properties panel. Enter 8 pixels as both width and height of the square. You will see the fields marked W and H that serve for this purpose. This is easier to do than to try to draw a precise dimension with the Rectangle tool.

Entering the dimensions of the square manually.

9 Also, as in the image above, make sure that the position of the square (its X and Y coordinates) are set to round numbers. This means that after the point, at the end of the number, there must be a zero, not any other number.

Why is this necessary? Because fine and precise elements as this hairline square will rend badly if they're not positioned on round coordinates. This is also true for any pixel or bitmap fonts, sharp images, etc.

10 Select the Line tool (N). The type of line for this tool should be hairline also. Below the square, draw a line that is slightly longer than the width of the stage. Click and drag while holding Shift to make a perfectly horizontal line. In the Properties panel, check that the line is positioned on round coordinates (X and Y).

The image below is a screenshot resized a little bit, made so not to occupy too much space. That's why it looks a little blurry - let that not confuse you.

A horizontal line on the scene.

11 Select the line by clicking once on it once with the Selection tool (V). Hold Shift and use the arrow keys on your keyboard to move the line left of the square. Position the line so that it falls exactly in the middle of the square on its left side. Release Shift and use the arrow keys to move the line by 1 pixel, for precise adjustements. The image below shows the portion of the stage where the line and the square connect.

A line connecting to a square.

The line should be connected to the square. How do you know if it is connected? Simple. Click anywhere on the stage to unselect it. Then double-click on the line, and if the square is selected too, it means they are connected.

Selected shapes.

12 Click anywhere to unselect the shapes. Click on the line again, but once only. The square mustn't be selected now, only the line.

Press Ctrl+C to copy the line. Press Ctrl+Shift+V (or select Edit > Paste in Place) to paste a copy of the line exactly over the original.

Now don't click anywhere! πŸ™‚ Because if you do that, the copy and the original will merge into a single line.

13 To use the copy without losing it, just hold Shift and use the Right arrow key to move the line to the right of the square. Again, position it so that it connects to the square on its right edge.

Check if this new line is connected to the square by double-clicking on it. Everything drawn so far should be selected. If that is not the case, move the line until it falls into place.

Horizontal lines connect to the square.

14 Select the Line tool (N) again. Click with your mouse outside the stage, start dragging and draw a vertical line by holding down Shift. Make the line's height bigger than the height of the stage.

A vertical line lying outside the stage.

15 Move this line (with the aid of Shift and arrow keys like you did before) so that its bottom point is connected to the square's top edge. Also, it should be placed in the middle of its top edge.

Three lines connecting to the square.

You may be asking yourself, why is it important that both horizontal lines be longer than the stage's width and the vertical ones higher than the stage's height? This is done in order to ensure the continuity of the cursor.

Imagine, for example, a user moving his mouse to the stage's left edge. Suppose the line on the square's right side wasn't longer than the stage. The line's end would appear. And that would look lame. You want your cursor to look connected to the edges of your movie at all times.

Of course, you may just want to make a simpler cursor, like a standalone crosshair or anything you like. But in this particular tutorial, I want to show you how to make a cursor that is linked to the edges of your movie. OK? πŸ™‚ Nice. Let's move on.

16 Using the Selection tool (V) click on the top line you just made, once, to select it.

17 Copy this line by pressing Ctrl+C and paste it in place by pressing Ctrl+Shift+V.

18 Move the line down by holding Shift while pressing the down arrow key. Place the line so that its top connects to the square's bottom side.

Four lines and a square.

Once again, check if everything's connected by double-clicking on the bottom line with the Selection tool (V).

All the content selected.

19 If you unselected everything by accident, select it again by pressing Ctrl+A.

20 Convert the drawing to a symbol by selecting Modify > Convert to Symbol or pressing F8.

The Convert to Symbol window.

In the window that appears, select Movie clip as type and enter crosshair cursor as the symbol's name. Before clicking OK, be sure to have selected the central little square as the symbol's registration point.

This is the little black square that you can see in the image above, in the Registration part of the window. I will explain you the importance of this later, for now, know that this option will make possible for your cursor to be exactly where the user's mouse is. Click OK.

21 With the newly created movie clip still selected, go to the Properties panel. On the panel's left side, you will see the input field which reads "Instance name".

Type in crosshair and hit Enter to confirm.

Assigning an Instance name to a movie clip.

Without an Instance name, a movie clip couldn't be controlled via ActionScript.

An Instance name is given to a movie clip, a button or a text field, so that it can be controlled via ActionScript. The Library name of a symbol ("crosshair cursor" in the case of the above movie clip) has nothing to do with ActionScript. It is there just so that you can find your movie clip among others in Library. The Instance name is what counts if you wish to manipulate your symbols via ActionScript. Also, this name is case-sensitive. So you must write it in ActionScript exactly the same as it appears in the Properties panel. And don't use any special characters, like spaces, hashes, dots, ampersands and such when assigning Instance names.

Top of page

Creating a dynamic text field that will display cursor's coordinates

22 Lock this layer. Create a new layer and call it text field.

Making a new layer.

23 Select the Text tool (T). In the Properties panel, on the left side, choose Dynamic text. You need to have a dynamic text field if you wish to write text via ActionScript.

Selecting the Dynamic text option.

Also, choose any font you like, even exotic and unusual ones. You'll see soon why. Don't select a big font size. Make it 12 or less.

24 Click and drag in the upper right part of the stage to create a dynamic text field. Make sure the text field's big enough so that two rows of text can be written inside it.

A dynamic text field created on the scene.

25 Hit Esc to exit text editing mode. You will see the text field represented by a light blue border, with handles around it.

26 Go back to the Properties panel. Assign an Instance name to this text field. Type in coordsDisplay and hit Enter to confirm.

The Instance name of a dynamic text field.

Only dynamic and input text fields can have Instance names. Static text fields cannot have an Instance name. They don't need it, because they are only used to display text that doesn't change, like link labels for sections of a site, titles and such.

27 Go to the right side of the Properties panel. Click the Embed button.

Embedding characters in a dynamic text field.

Select the Numerals category in the list. Then, in the "Include these characters" field, type in X, Y (both uppercase), : (semicolon) and press space once. That's right, you also have to include a space so that Flash can know how to write it out in the dynamic text field later, because a blank space character is different for each font. Click OK.

The step you just accomplished is necessary if you want every single user to see your font exactly as you see it on your computer. For widely available fonts, like Arial or Times New Roman, you don't have to use this technique, because you can expect that the majority (but not everyone!) of your users will have that font installed on her or his machine.

If you use an exotic font which is unlikely to be installed on an average user's computer, and don't embed it, that person's machine will display the default font. Which is, for Windows users, Times New Roman. Now imagine your cooly designed awesome hi-tech site having Times New Roman displayed somewhere where a pixel font should be expected. An abomination, huh? πŸ˜‰

If you need a font to be embedded in a field, never embed all the characters. That doesn't make any sense. Select just the ones you need. Most of the time this will be letters, numbers and punctuation, including an @ sign and such. You really don't need kanji or devanagari characters if you're site is in english language. Because the more characters you add, the more bigger the size of your final SWF file will be. The final SWF resulting from this tutorial is just 755 bytes in size! Now ain't that cool? πŸ™‚ I tried embedding all the characters. That file had at the end the size of 640 KB!

28 In the menu at the left of the Embed button, choose Bitmap text if you're using a pixel or bitmap font. Select Anti-alias for animation if you are using a non-bitmap font, like Arial and such.

Lock this layer.

Top of page

Writing the ActionScript that makes your custom cursor replace the mouse

29 Make a new layer and call it actions. You can lock it because ActionScript can be put inside it, whether it is locked or not.

Locking it prevents you from accidentally putting a symbol in it or drawing something inside it. I always reserve a layer for ActionScript only, and also I put it on top of all the other layers so that I can easily find it in more complex projects.

30 Click on the layer's first (and only) keyframe to select it.

Selecting a keyframe for ActionScript input.

31 Hit F9 or select Window > Actions to open the Actions panel. Write in the following ActionScript code:

Mouse.hide();
crosshair.startDrag(true);
_root.onMouseMove = function() {
coordsDisplay.text = "X: " + _xmouse + "\nY: " + _ymouse;
}

You'll see a small letter "a" appear on the keyframe you just selected in the previous step. This indicates that there's ActionScript code placed on this keyframe.

32 Test your movie by selecting Control > Test Movie. Move your mouse over your flash movie. You'll see the crosshair cursor move (with no sign of the standard arrow cursor whatsoever), and the coordinates being displayed!

You'll now easily understand how this cursor moves. Please, proceed onto the explanation πŸ™‚

Top of page

Explaining the code behind the cursor and the coordinates

The first line of the code,

Mouse.hide();

hides the mouse - the standard cursor of the operating system, be it Windows, Mac or Linux. When manipulating the Mouse object, you don't need to create a new Mouse object, like you do, for example, for the Date object (see what I mean by checking out my antique analog clock tutorial).

Why? The explanation is simple: there can't more then one Mouse object in Flash, because this Mouse object is referring to the computer's real physical mouse. Ever seen a computer with two mouses? Even saying the plural, mouses, in relation to a computer sounds funny πŸ™‚

The next line,

crosshair.startDrag(true);

tells Flash to start dragging the crosshair movie clip. You do that by first writing the Instance name of the movie clip you want to replace the standards cursor (crosshair in this case), then the command, separated by a dot.

The command (or method, in proper programming jargon) startDrag has a parameter within paretheses. This parameter can be set to either true or false. When you set it to true, you tell Flash that this movie clip will be dragged by its registration point. Try setting it to false, test your movie and see what happens.

Your crosshair cursor will be dragged by the point where your mouse entered the zone of the Flash movie. This means a different place every time. That's why you have to put it to true, otherwise your cursor won't make much sense. This is why you had to set the movie clip's registration point to its center, back when you created it in step 20 of this tutorial.

The remaining lines of ActionScript display the cursor's (or mouses, it is the same) coordinates in the dynamic text field.

_root.onMouseMove = function() {
coordsDisplay.text = "X: " + _xmouse + "\nY: " + _ymouse;
}

The first line uses the _root reference. This particular keyword references the main timeline. You could have used any movie clip with an Instance name. I just decided to use _root. So, the main timeline (_root) can use and react to any movie clip events like any movie clip would.

An event is something that happens while the movie is running. It can be many things, like a click of the mouse, a keystroke, a sound reaching its end and so on. For this particular project, you are using the onMouseMove event. This event happens every time a user moves his mouse. So, by saying

_root.onMouseMove = function() {

you are assigning a function to the _root's onMouseMove event. That means every time the mouse is moved, this function will execute. And what will exactly execute? Every line of code placed between the function's curly braces - { and }.

Inside the function's curly braces, you have a single line of code:

coordsDisplay.text = "X: " + _xmouse + "\nY: " + _ymouse;

The coordsDisplay.text = piece of code means "the text that will appear in the coordsDisplay text field is as follows...". On the right side of the equals sign follows what will be shown in the coordsDisplay text field.

Now, everything that is between quotation marks will be displayed literally. That means, the text will begin with X:. Then you have a keyword, _xmouse.

The _xmouse keyword serves for retrieving the current X (horizontal) coordinate of the user's mouse. It is a value expressed in pixels. The left edge of the stage is X coordinate zero. To its left, this number increases. To its right, it decreases, meaning its value becomes negative (like -1, -14, -100 and so on).

If you write the _xmouse keyword between the quotation marks, it will be displayed literally, as "_xmouse" and there will be no mouse position! Keywords are never written between quotation marks, like Instance names, too.

Then you have a literal value, again. But is is a little strange. Why don't the backslash and the letter n appear when the movie is running? Simple. the \n is the new line character. It means, when you write it, all text that follows it will be placed on the next line, below the text that precedes it.

Then you have the letter Y followed by a semicolon. You can write anything, like "coordinate Y" or "vertical position". Just remember to embed all the characters that you ar going to use in the dynamic text field..

At the end you have the _ymouse keyword, which is used for retrieving the vertical position of the mouse (cursor). Note that the number increases as you move your mouse down, because in Flash, the top stage edge is the zero Y coordinate.

That's about it! Have fun making your own cursor, animate it, make it change its color. Remember that your imagination has no limits!

Oh yes, there is one little detail that I want to show you. Test your movie by pressing Ctrl+Enter. Don't move your mouse. You'll see that there isn't any text at all appearing in your movie. Why is that? Because it is only displayed once the mouse is moved.

So, if you want to have "X:" and "Y:" appear at the beginning, put this simple line of code before all current code - on top of it:

coordsDisplay.text = "X: " + "\nY: ";

Download the zipped source FLA file explained in this lesson.

Also, you can download the source file for the blinking cursor.

Comments

Submit a comment

  • Doug Nov 12, 2008 at 12:06 pm

    Luka,

    This tute has been extremely helpful. I use lyda.comtraining videos but this written tutorial, with explaination of actionscript, works for me at my current skill level. Thanks..

    Doug

  • Luka Nov 18, 2008 at 10:51 am

    Doug: Stick around. Learning from different sources is cool, as you progress you will find advanced tutorials here.

  • Doug Dec 1, 2008 at 10:49 am

    Luka,

    Any chance you could suggest how to keep the scanning cursor from continually triggering a mc? Everything you explained works great but when I roll the cursor over a mc it triggers the mc over and over as I roll over the hit spot. I’m using a mc instead of a button. I want the mc to play only once while in the area. Make sense?

    Here’s my code.

    Mouse.hide();
    crosshair.startDrag(true);

    btn_mc.buttonMode = true;
    btn_mc.addEventListener(MouseEvent.ROLL_OVER, onButtonOver);
    btn_mc.addEventListener(MouseEvent.ROLL_OUT, onButtonOut);

    btn1_mc.addEventListener(MouseEvent.ROLL_OVER, onButtonOver);
    btn1_mc.addEventListener(MouseEvent.ROLL_OUT, onButtonOut);

    function onButtonOver(e:MouseEvent):void

    {
    e.currentTarget.gotoAndPlay(“over”);
    }

    function onButtonOut(e:MouseEvent):void

    {
    e.currentTarget.gotoAndPlay(“out”);
    }

    btn_mc.addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler);
    function mouseDownHandler(event:MouseEvent):void

    {
    navigateToURL(new URLRequest(“http://www.arcutech.com”));
    }

  • braj Jan 6, 2009 at 3:52 am

    why mouse cursor always down in left side , what mechanism

  • monika Jul 12, 2010 at 5:40 am

    Hi

    In my flex chart i need to show a crooshair cursor.
    similar to the “http://www.rb.com/Media-investors/Share-price-information/Share-price-graph” crosshair cursor however this is developed in java script and i need it in action script.
    Could you please help me in this asap?

    Thanks

  • Renfield Jun 6, 2011 at 2:50 am

    wow this is really cool, but is it possible to change it into a .cur or .ani file?

  • DJ remixes Sep 12, 2011 at 1:17 pm

    Really enjoyed your piece, appreciate it.

You must log in to post a comment.