1. Code
  2. ActionScript

Quick Tip: How to Detect Mouse Direction Using ActionScript


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.


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:

Step 4: Main Function

This is the main function:

Step 5: Check Direction

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

Step 6: Get Directions

Check the mouse directions.

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.

Step 8: Document Class Version

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 "", then you can reference it using the following snippet:


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

Thanks for reading.

Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.