I have some difficulties using custom event listeners.
What I would like to achieve is pretty simple. With a bunch of movable fruits, when dragging one of them(this becomes the ‘active’ object) to collide with others(these are the ‘inactive objects’), I need Flash to tell me who is colliding whom.
So I setup the Fruit Class, with the ability to dispatch and listen the custom event: “EXECUTE_HITTEST”. For me the code looks good, but there’s must be something wrong…
It should be a very simple thing like forgotten to setup something, but owing to my skinny Flash skills, just can’t figure it out.
The current setup snapshot is here, while the full .fla & .as source can be downloaded [URL=“http://www.driveway.com/v4j4e3x3k3”]here. (also bundled with this post below)
The complete Fruit.as is also bundled here for convenience:
package
{
import flash.display.MovieClip;
import flash.events.MouseEvent;
import flash.events.Event;
public class Fruit extends MovieClip
{
public function Fruit()
{
initListeners();
}
private function initListeners():void
{
this.addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHdlr);
this.addEventListener(MouseEvent.MOUSE_UP, mouseUpHdlr);
//setup the default collision detection listener
this.addEventListener("EXCUTE_HITTEST", executeHitTestHdlr);
}
private function mouseDownHdlr(e:MouseEvent)
{
trace("====== " + this.name + " ======= mouse downed.");
//temporarily disable the C.D. listener when the object becomes 'active'
this.removeEventListener("EXCUTE_HITTEST", executeHitTestHdlr);
//dispatch the "EXECUTE_HITTEST" event based on mouse-moving
this.addEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHdlr);
startDrag();
}
private function mouseUpHdlr(e:MouseEvent)
{
trace("====== " + this.name + " ======= mouse uped.");
//restore the C.D. listener when the object becomes 'inactive'
this.addEventListener("EXCUTE_HITTEST", executeHitTestHdlr);
//stop dispatching the "EXECUTE_HITTEST" event
this.removeEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHdlr);
stopDrag();
}
// the active object will dispatch the "EXECUTE_HITTEST" EVENT
// when it gets moved
private function mouseMoveHdlr(e:MouseEvent)
{
dispatchEvent(new Event("EXCUTE_HITTEST"));
e.updateAfterEvent();
}
//once inactive objects receive the event, they will do the C.D. checking
private function executeHitTestHdlr(e:Event):void
{
// this= inactive obj.
// e.target = active obj.
trace("----in executeHitTestHdlr-----");
trace("e.target= " + e.target + " name: " + e.target.name); //active obj.
trace("this= " + this + " name: " + this.name); //inactive obj.
if (e.target is Fruit)
{
trace(this.hitTestObject(e.target as Fruit));
}
}
} //EOB class
} //EOB pkg
T.I.A.