TrackingTheMouse

Tracking the Mouse
A few of you have created games with controls that are keyboard based, and they might feel a bit sluggish to you, particularly if your game was one that was originally using the "paddle" controller. Another option is to track the mouse.

Here's how to do this. First, you'll need to import another library into your main program: code format="actionscript3" import flash.ui.Mouse; code Then, you'll need to set up a mouse listener event in your main program's constructor: code format="actionscript3" stage.addEventListener(MouseEvent.MOUSE_MOVE, handleMouseMove); code This will cause the program to call the "handleMouseMove" function (which you are about to write) whenever the mouse is inside the bounds of the movie and has just changed position. Then write the handleMouseMove function. In this case, I am going to make it move a ball around the screen. code format="actionscript3" public function handleMouseMove(mEvt:MouseEvent) {   myBall.x = mEvt.stageX; myBall.y = mEvt.stageY; } code ... and this should work.

If you only want to move the object around in one dimension (for an object moving up and down only, for example, just use the "y" line - or the "x" line, as appropriate.

Hiding the mouse
This is neat, but now you have the arrow hanging out on top of the object you are tracking, which kind of loses some of the immersion. In flash, you can easily fix this by saying the following in your constructor: code format="actionscript3" Mouse.hide code This will make the mouse disappear - in fact it might even make it look like your object is the mouse, depending on how you pick the appearance of your object. Note: if you are running a multiframe game, you might wish to say "Mouse.show" before you leave the game screen. It is very disconcerting to lose sight of the mouse when you are supposed to be pressing a button!

Listening to the mouse button
We've seen mouse button effects before, but they might be worth mentioning again. In addition to the MOUSE_MOVE event, there are also MOUSE_UP and MOUSE_DOWN events. You can use these to detect when the user presses the mouse button: code format="actionscript3" stage.addActionListener(MouseEvent.MOUSE_UP, handleMouseClick); code This will call your handleMouseClick function (which you would need to write) whenever the user releases the Mouse.