2007年6月6日星期三

Creating a mouseWithin Event

There are times where you might want to have actions only run when the mouse is within a sprite or movie clip. Director's Lingo programing language has a mouseWithin event that facilitates this. Flash, however, has no such event. However, with ActionScript 3's event model, you can easily create your own.

A mouseWithin event is essentially an enterFrame event that only runs when the mouse is within or touching the display object in which its associated. So, in making your own, all you need to do is define an enterFrame event when the mouse enters the object and remove it when the mouse leaves the object. And yes, technically you could do this in ActionScript 1 and ActionScript 2, but it would mean using up event handlers like onRollOver and onEnterFrame which could interfere with other actions for your movie clip (since you can only have one per movie clip).

For ActionScript 3, implementing a mouseWithin event just means giving your sprite or movie clip class a few event handlers and setting up some listeners, e.g.

ActionScript Code:

// methods managing mouseWithin
private function addMouseWithin(event:MouseEvent):void {
addEventListener(Event.
ENTER_FRAME, mouseWithin);
}
private function removeMouseWithin(event:MouseEvent):void {
removeEventListener(Event.
ENTER_FRAME, mouseWithin);
}
private function mouseWithin(event:Event):void {
dispatchEvent(new MouseEvent(
"mouseWithin"));
}

// in constructor
public function MySpriteClass() {
addEventListener(MouseEvent.
MOUSE_OVER, addMouseWithin);
addEventListener(MouseEvent.
MOUSE_OUT, removeMouseWithin);
}


With that, a mouseWithin event fires every frame whenever the mouse is within the sprite. To add listeners for it, just use:

ActionScript Code:

addEventListener("mouseWithin", mouseWithinHandler);


0 评论: