# Quick Tip: How to Detect Mouse Direction Using ActionScript

##### Tutorial Details
• Program: Flash
• Difficulty: Beginner

In this Quick Tip you will learn how to get the mouse’s current direction in your Flash application using AS3. You could use this to create an interesting control method for a game, using a mouse like a joystick, for example. For now we will just display the direction on screen.

## Preview

Here’s a quick example to demonstrate what we’re working towards:

## Brief Overview

Using a MouseEvent.MOUSE_MOVE event we’ll monitor the movement of the mouse cursor, store the data in variables and display its current direction.

## Step 1: Create a New File

Open Flash and create a new Flash File (ActionScript 3).

## Step 2: Open Actions Panel

Press Option + F9, or go to Window > Actions to open the Actions Panel.

## Step 3: Variables

Enter the variables we’ll use; their names are fairly self-explanatory:

var previousX:Number = 0;
var previousY:Number = 0;
var currentX:Number = 0;
var currentY:Number = 0;
var xDir:String;
var yDir:String;
var dir:TextField = new TextField();

## Step 4: Main Function

This is the main function:

function getMouseDirection():void
{
dir.width = stage.stageWidth; //Size of the textfield
addChild(dir); //Adds the textfield to the stage

//Adds a mouse move listener to the stage and executes the checkDirection function when a mouse movement occurs
}

## Step 5: Check Direction

This code calls the functions which check the direction and displays the result in the stage TextField.

function checkDirection(e:MouseEvent):void
{
getHorizontalDirection();
getVerticalDirection();

dir.text = "x: " + xDir + ", y: " + yDir;
}

## Step 6: Get Directions

Check the mouse directions.

//Horizontal
function getHorizontalDirection():void
{
previousX = currentX; //Checks the last position
currentX = stage.mouseX; //Gets the current position

if (previousX > currentX) //Compares both positions to determine the direction
{
xDir = "left";
}
else if (previousX < currentX)
{
xDir = "right";
}
else
{
xDir = "none";
}
}

//Vertical
function getVerticalDirection():void
{
previousY = currentY; //Checks the last position
currentY = stage.mouseY; //Gets the current position

if (previousY > currentY) //Compares both positions to determine the direction
{
yDir = "up";
}
else if (previousY < currentY)
{
yDir = "down";
}
else
{
yDir = "none";
}
}

## Step 7: Running the Function

To start the function, add this line to the code. Once the getMouseDirection() function is run, it’ll set up the MOUSE_MOVE event listener that powers the direction indicator.

getMouseDirection();

## Step 8: Document Class Version

package
{
import flash.display.MovieClip;
import flash.text.TextField;
import flash.events.MouseEvent;

public class MouseMoveDemo extends MovieClip
{
public var previousX:Number = 0;
public var previousY:Number = 0;
public var currentX:Number = 0;
public var currentY:Number = 0;
public var xDir:String;
public var yDir:String;
public var dir1:TextField = new TextField();
public var dir2:TextField = new TextField();

public function MouseMoveDemo()
{
getMouseDirection();
}

public function getMouseDirection():void
{
dir1.width = stage.stageWidth;
dir2.width = stage.stageWidth;
dir2.y = 50;
}

public function checkDirection(e:MouseEvent):void
{
getHorizontalDirection();
getVerticalDirection();

dir1.text = "x: " + xDir
dir2.text = "y: " + yDir;
}

public function getHorizontalDirection():void
{
previousX = currentX;
currentX = stage.mouseX;

if (previousX > currentX)
{
xDir = "left";
}
else if (previousX < currentX)
{
xDir = "right";
}
else
{
xDir = "none";
}
}

public function getVerticalDirection():void
{
previousY = currentY;
currentY = stage.mouseY;

if (previousY > currentY)
{
yDir = "up";
}
else if (previousY < currentY)
{
yDir = "down";
}
else
{
yDir = "none";
}
}

}

}


Opt for this approach if you’d prefer to use a document class rather than timeline code. Read this Quick Tip if you’re not sure what to do with it.

You could use this class to embed a mouse direction indicator inside any project. Just copy the whole class into a new AS file, save it as “MouseMoveDemo.as”, then you can reference it using the following snippet:

var mouseMoveDemo:MouseMoveDemo = new MouseMoveDemo();


## Conclusion

This is a basic example of how you can use such a function; try it out, experiment and use it in your own projects!

Tags: Tips

Hey thats a neat trick. Thanks..

• Pingback: uberVU - social comments

• http://www.dcomsoft.com Alex

Thank you. Nice tip.

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

Pretty easy and nice code dude. Thanks for this quick guide. Regards.

• http://www.im-school.com Ali

this is a lot of code for just a very simple task !

• Mathias

I don’t think its much code at all

• Mark
• Dave

Nice simple tut. Thanks :-)

• John Lenin

Carlos is a bad coder . He just copies and pastes . I don’t think he’s getting any jobs at all

• http://michaeljameswilliams.com/ Michael Williams

Hey John,

This is not the place for accusations about how much work the author’s getting. If you want to comment about the site, the opinions of the author or another commenter, or the post itself, that’s fine — but no personal attacks.

-Michael (Technical Editor)

• http://scriptinaction.wordpress.com krishna

I don’t know but it not work properly…………plz try to describe

• http://www.get-it-dun.com Lewis Cowles

here is the wonderFL code to this tutorial, it’s more OOP and you can define X or Y sensitivity as well as configure an update timer

http://wonderfl.net/code/2fbeccf4084952467920a5cfba311140131fa3fb

hope you all like

• UUltraman

great work! nice and simple

• brichollo

The first version works fine but if i try the second version with the document class, i get error 1046! I’ve tried everything to find a fault but the second version is not for download here :(

• http://michaeljameswilliams.com/ Michael Williams

That’s embarrassing; I wrote the second one! I should know better…

Anyway, fixed now. I had missed an “import flash.events.MouseEvent;” call at the top.

(You will also need to place two dynamic text fields on the stage, and give them instance names of dir1 and dir2.)

• MyPassionAS

Hi Carlos,

Nice tutorial. I am new to AS3, i found something that was not mentioned in the tutorial while i was reading.

I noticed is that you displayed on line 34,35 you didn’t mentioned that you took 2 textbox with instance name dir1 and dir2 in which you displayed the mouse direction while you created only one textfield dynamically. Pls add this so that reader can easily get without downloading the source files first.

• http://michaeljameswilliams.com/ Michael Williams

Heh, man I really screwed up the document class version huh?

Thanks for pointing that out! I’ve corrected it and tested it, and it’s working now :)

• http://WWW.LUISDIEGORE.COM Diego

I’m sure i did everything right, i put a trace() command inside the constructor of the class MouseMoveDemo…when i execute the movie, the trace works fine, but shows up this error…

————————————-
TypeError: Error #1009: No se puede acceder a una propiedad o a un método de una referencia a un objeto nulo.
at MouseMoveDemo/getMouseDirection()
at MouseMoveDemo()
at Main()
———————————

I made an AS file called “Main.as”, and put the snipet you did inside of the constructor of the Main class:

————————————–
public function Main()
{
var mouseMoveDemo:MouseMoveDemo = new MouseMoveDemo();
}
————————————–

If anyone can help me, Thanks…

• http://michaeljameswilliams.com/ Michael Williams

This tut will be the death of me… ;)
I reckon this is to do with “stage”. Try this. Instead of:

public function MouseMoveDemo()
{
getMouseDirection();
}

…do this:

public function MouseMoveDemo()
{
}
{
getMouseDirection();
}

I’ve noticed this happen in CS5 but not CS3. Not sure why. Anyway, I hope that fixes it!

(Oh, don’t forget to import flash.events.Event.)

• Rodrigo

Hello,
Good tutorial. Simple and clear.
Perhaps this library is interesting when you want to have more control over the movement of the mouse:
Mouse Gesture Recognition by Didier Brun
http://www.bytearray.org/?p=91

• moudi

lol
im kinda new to actionscript 3 :D
i love it
and am trying to make a ball follow the mouse
the only problem i m facing is when the ball reaches the mouse position
it stops
what shall i do to make it continue its position
then moves again when the mouse moves ?