不用startDrag和stopDrag的对象拖动

package {
    import flash.display.Sprite;
    import flash.events.MouseEvent;
    import flash.ui.MouseCursor;
    import flash.ui.Mouse;
 
    public class MouseMoveDrag extends Sprite {
 
        private var offsetX:Number;
        private var offsetY:Number;
        private var arrBalls:Array;
        private var _draggedBall:Ball;
 
 
        public function MouseMoveDrag():void {
 
            arrBalls=new Array(7);
 
            for (var i:uint=0; i<arrBalls.length; i++) {
                arrBalls[i]=new Ball(20+Math.random()*30,Math.random()*0xffffff);
                arrBalls[i].x=stage.stageWidth*Math.random();
                arrBalls[i].y=stage.stageHeight*Math.random();
                arrBalls[i].addEventListener(MouseEvent.MOUSE_DOWN, MouseDownHandler);
                arrBalls[i].addEventListener(MouseEvent.MOUSE_UP, MouseUpHandler);
                arrBalls[i].addEventListener(MouseEvent.MOUSE_OVER,MouseOverHandler);
                arrBalls[i].addEventListener(MouseEvent.MOUSE_OUT,MouseOutHandler);
                addChild(arrBalls[i]);
            }
 
        }
 
        function MouseOverHandler(e:MouseEvent):void {
            Mouse.cursor=MouseCursor.BUTTON;
        }
 
        function MouseOutHandler(e:MouseEvent):void {
            Mouse.cursor=MouseCursor.AUTO;          
        }
 
        //开始移动
        function MouseDownHandler(e:MouseEvent):void {
            offsetX=e.localX;
            offsetY=e.localY;           
            _draggedBall = e.target as Ball;
            stage.addEventListener(MouseEvent.MOUSE_MOVE, stageMouseMoveHandler);
        }
 
        //停止拖动
        function MouseUpHandler(e:MouseEvent):void {
            _draggedBall = null;
            //拖动完成后,移除舞台的Mouse_Move监听
            stage.removeEventListener(MouseEvent.MOUSE_MOVE, stageMouseMoveHandler);
        }
 
 
        function stageMouseMoveHandler(e:MouseEvent):void {
            //trace(e.target);
            var _ball:Ball=e.target as Ball;
            if (_ball!=null) {
                //设置新的坐标
                _ball.x=mouseX-offsetX;
                _ball.y=mouseY-offsetY;
            }
            else {
                //trace("您拖得太快了!" + _draggedBall.toString());
                if (_draggedBall!=null){
                    _draggedBall.x=mouseX-offsetX;
                    _draggedBall.y=mouseY-offsetY;
                }
            }
        }
 
    }
}

你可能感兴趣的:(不用startDrag和stopDrag的对象拖动)