Monday, November 15, 2010

Creating a mouse trail using AS3

Today we will create a simple mouse trail.

Here is an example (move your mouse around the flash area):

It is pretty simple to do this - we have an object being spawned at the mouse location every time the user moves his mouse. In my case - the object is a gradient circle. Set its class name as Circle.

Here's my code:

import flash.display.MovieClip;

stage.addEventListener(MouseEvent.MOUSE_MOVE, spawnTrail);

var allCircles:Array = [];

function spawnTrail(MouseEvent):void
var aCircle:MovieClip = new Circle();
aCircle.x = mouseX;
aCircle.y = mouseY;

stage.addEventListener(Event.ENTER_FRAME, manageTrails);

function manageTrails(Event):void
for (var i:int = 0; i< allCircles.length; i++)
if (allCircles[i].alpha >= 0)
allCircles[i].alpha -=  0.1;

if (allCircles[i].alpha <= 0)

As you can see, I create an instance of the Circle object every time the mouse is moved. Then I add it to an array of all trail circles. The elements of array are updated every frame - they become more transparent and when they are completely invisible, they get removed from display list and the array.

If you want the circles to be constantly spawning - use Event.ENTER_FRAME instead of MouseEvent.MOUSE_MOVE.

Thanks for reading!


Cristian VĂ©lez said...

Hey man! ... well, i'm beginner in this of ActionScript, so i have some questions about your code... first, i tried to do it using flash develop: i copied and pasted it in a .as file and used it as the main class, but it shouted me many mistakes, for example with the Circle class, and with an expecting leftbrace in this line "function spawnTrail(MouseEvent:(void" or something like that... i wish you could answer me so i can use your code by myself.. thank you very much!

Alien_AV said...

you'd better reuse the old circles, this code accumulates lots of them until gc, which makes it really slow

Post a Comment