Tuesday, February 15, 2011

AS3: Detecting if the Mouse is Idle or Not Moving

In ActionScript 3, you can use MouseEvent.MOUSE_MOVE in order to detect when the user moves the mouse in your Flash movie, but I needed something that could detect the opposite. I needed to check whether the mouse was idle or not moving. I needed to find a way to check if the mouse pointer is being still and is just staying put in the same spot. So I noodled around a bit with some code, and what I came up with was an ENTER_FRAME event listener that would constantly check for the current x and y positions of the mouse pointer to see if the values were changing. To be able to check if the values were changing, I created 2 variables for each of the coordinates - 2 variables for the x coordinates, and 2 variables for the y coordinates. I made 2 sets so that I could compare them to see if the position of the mouse pointer has changed. I had posXa & posXb for the x coordinates, and posYa & posYb for the y coordinates. And then I used stage.mouseX and stage.mouseY to alternately assign the current position of the mouse pointer to the 2 sets of variables every time the ENTER_FRAME event gets triggered. The first time the ENTER_FRAME event listener runs, the location of the mouse pointer is assigned to posXa and posYa. Then the next time it runs, the location is assigned to posXb and posYb instead. And then it just continues to alternate each time the ENTER_FRAME event gets dispatched. I have a switcher variable, which is just an integer that switches back and forth between 0 and 1, and I am using that to tell Flash to alternately assign the values to either set. The idea here is to constantly check whether the values in set A and set B are the same or not. If they are, it means that the mouse is in the same spot, and is therefore not moving. Here's the code:
var switcher:int = 0;
var posXa:Number = stage.mouseX;
var posYa:Number = stage.mouseY;
var posXb:Number = stage.mouseX;
var posYb:Number = stage.mouseY;

this.addEventListener(Event.ENTER_FRAME, checkMovement);

function checkMovement(e:Event):void
{
     if (switcher == 0)
     {
          posXa = stage.mouseX;
          posYa = stage.mouseY;
          switcher = 1;
     }
     else
     {
          posXb = stage.mouseX;
          posYb = stage.mouseY;
          switcher = 0;
     }

     if (posXa == posXb && posYa == posYb)
     {
          trace("not moving");
     }
     else
     {
          trace("moving");
     }
}

1 comment: