Is there an event for when a MovieClip changes position?
I'd like to be notified when a MovieClip changes position, regardless of whether the position was changed by m开发者_运维技巧y code, or by the built-in drag operations. Is there such an event?
There's none built in. You have basically 2 main options:
1) Either poll repeatedly to check if the position has changed. 2) Create a new class that extends MovieClip and override the set x and y properties to fire an event:
public class PosNotifyMC extends MovieClip
{
// the name of the event we're firing
public static const MOVED:String = "moved";
// override the set x property
override public function set x( n:Number ):void
{
super.x = n;
this.dispatchEvent( new Event( PosNotifyMC.MOVED ) );
}
// override the set y property
override public function set x( n:Number ):void
{
super.x = n;
this.dispatchEvent( new Event( PosNotifyMC.MOVED ) );
}
}
If your position is changing a lot, then keep a local event and repeatedly fire that instead of creating a new one every time. You can also create a new Event class that holds the updated position if you wanted as well.
+1 @divillysausages :)
then you can do something dirty and monitor "manually" the changes.
the MovieClip class is dynamic so we can create variables to store the last X/Y position then perform a delta on EnterFrame. if the delta is not 0 then the clip has moved.
that's really ugly:
package
{
import flash.display.MovieClip;
import flash.display.Sprite;
import flash.events.Event;
import flash.events.MouseEvent;
public class Mover extends Sprite
{
private var mc:MovieClip;
public function Mover()
{
mc = new MovieClip();
mc.graphics.beginFill( 0xCC00FF );
mc.graphics.drawRect( 0, 0, 50, 50 );
addChild( mc );
//storing dynamic properties
mc.lx = mc.x;
mc.ly = mc.y;
//and add monitoring function
mc.addEventListener( Event.ENTER_FRAME, onEnterFrameHandler );
mc.addEventListener( MouseEvent.MOUSE_DOWN, mouseHandler );
mc.addEventListener( MouseEvent.MOUSE_UP, mouseHandler );
//move clip from outisde
// this.addEventListener( Event.ENTER_FRAME, moveClipHandler );
}
private function moveClipHandler(e:Event):void
{
mc.x++
}
private function mouseHandler(e:MouseEvent):void
{
switch( e.type )
{
case MouseEvent.MOUSE_DOWN: ( e.target as MovieClip ).startDrag(); break;
case MouseEvent.MOUSE_UP: ( e.target as MovieClip ).stopDrag(); break;
}
}
private function onEnterFrameHandler(e:Event):void
{
var m:MovieClip = e.target as MovieClip;
//check the delta
if ( m.x != m.lx || m.y != m.ly ) trace( 'moved!' );
m.lx = m.x;
m.ly = m.y;
}
}
}
but it works :)
it would be a good idea to centralize the delta checks in a class that would give the abilty to register / unregister clips and DisplayObjects as needed.
精彩评论