Download

How can I get mouse position in Flash before a MouseEvent is detected?

Today I decided to revisit a problem I’ve had since my first day moving the mouse in a Flash movie. When the movie starts, it doesn’t know where the mouse is, and the mouse gets drawn at (0, 0) until I move the mouse and it jumps to where it’s supposed to be.

I detect the mouse location with code like this:



function handleMouseMove( e:MouseEvent ):void 
{
    mCursor.x = e.stageX;
    mCursor.y = e.stageY;
}

stage.addEventListener( MouseEvent.MOUSE_MOVE, handleMouseMove, false, 0, true );


…where mCursor is a symbol that I use as my mouse cursor.

The code works fine after I’ve moved the mouse, but until I move the mouse, it stays at (0, 0) in the top-left corner.

I’ve tried setting the mouse location before the MouseEvent.MOUSE_MOVE fires:



mCursor.x = stage.mouseX; // Doesn't work
mCursor.y = stage.mouseY;// Doesn't work

mCursor.x = root.stage.mouseX; // Doesn't work
mCursor.y = root.stage.mouseY; // Doesn't work

mCursor.x = ExternalInterface.call("GetLastMouseX"); // I've also tried caching the last position in UnrealScript, but this doesn't work when I first start the game and open the main menu
mCursor.y = ExternalInterface.call("GetLastMouseY"); // I've also tried caching the last position in UnrealScript, but this doesn't work when I first start the game and open the main menu


I’ve decided to start hiding the mouse, and only showing it after the first MouseEvent.MOUSE_MOVE.



function handleMouseMove( e:MouseEvent ):void 
{
    mCursor.x = e.stageX;
    mCursor.y = e.stageY;
    mCursor.visible = true;
}

stage.addEventListener( MouseEvent.MOUSE_MOVE, handleMouseMove, false, 0, true );
mCursor.visible = false;


But I would love to know how to get the mouse position before there’s a MouseEvent.

Not sure why this isn’t working for you, as I get the mouse position simply like this:



var point:Point = new Point(stage.mouseX, stage.mouseY);


I’m using AS3 btw.

Btw, i would look into using the hardware mouse, rather than trying to render your own mouse cursor. The problem with this is your mouse movement will be lagged behind the hardware cursor, and movement will actually be reduced by frame drops (making menu nav very frustrating for players running at a low framerate). Using the hardware cursor makes your UI as responsive as using windows.

copy that. The more the performance the better.

Thanks. I’ll take a look at using the hardware cursor.