Thursday, July 8, 2010

How to create a proper cursor using Actionscript 3

A lot of flashes have custom cursors in them. Basically, it is just a movieclip following the coordinates of the mouse, however, several problems might occur, such as:

1) User is unable to hover/click/select any button or dynamic text.
This is because movieclips in AS3 (unlike in AS2) overlap buttons and don't let users click anything behind them.

2) The default cursor doesn't dissapear.
This usually happens when Mouse.hide(); isn't added in a frame loop.

3) Default cursor doesn't show up even when user moves mouse out of the flash area.
This happens when cursor dissapearance is controlled by a frame loop, but there is no code to reveal the cursor when it leaves the flash area.

This following code (commented) works well and without any of these problems:

// add the necessary listeners
stage.addEventListener(Event.ENTER_FRAME, mover); // frame loop
stage.addEventListener(Event.MOUSE_LEAVE, mouseleft); // mouse leaving flash
stage.addEventListener(MouseEvent.MOUSE_MOVE, mousethere); // mouse moving in flash

function mover(event:Event):void {
curs.x=stage.mouseX; // follow coordinates
curs.mouseEnabled=false; // to make buttons clickable, etc.
function mouseleft(event:Event):void {
curs.alpha=0; // cursor hides when out of screen; // default cursor appears when out of screen
function mousethere(event:Event):void {
curs.alpha=1; // cursor appears when in screen
Mouse.hide(); // default cursor hides when in screen

Results can be seen in the demo:

Note: The default cursor doesn't hide in Chrome when Flash is running in "opaque" or "transparent" wmode. It's a browser bug. To fix this, set your wmode to "window" (you don't need to change anything in the flash itself, just the html tag).

1 comment:

Post a Comment