Game Development Reference
In-Depth Information
How to register for a mouse event
Flash lets you handle the mouse event in an elegant way. Even if you had to
handle mouse events on 50-odd objects on the screen, with the combination
of object-oriented design, things can be kept clean and manageable.
First off, you need to determine which sprite, called the target, you want to trap the
mouse events in. Then you simply need to add event listener, like we saw for the
timers in the previous section.
First we create a simple sprite and then we register a listener for the mouse event.
We also write a listener callback function that simply prints the log to the console.
package
{
import flash.display.Sprite;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.ui.Mouse;
public class Main extends Sprite
{
public function Main():void
{
if (stage) init();
else addEventListener(Event.ADDED_TO_STAGE, init);
}
private function init(e:Event = null):void
{
removeEventListener(Event.ADDED_TO_STAGE, init);
// entry point
var s:Sprite = new Sprite();
s.graphics.beginFill(0x0000FF);
s.graphics.drawCircle(0, 0, 30);
s.graphics.endFill();
s.addEventListener(MouseEvent.CLICK, onClick);
s.x = 50;
s.y = 50;
addChild(s);
}
public function onClick(e:MouseEvent):void {
trace("Mouse Click Detected.");
}
}
}
 
Search WWH ::




Custom Search