as3.0 在一个范围之内拖动

import flash.events.MouseEvent;
import flash.geom.Point;
import flash.display.MovieClip;

//假设你的黑色元件是black,粉色元件是powder
//此变量指示当前鼠标左键是否按下
var down:Boolean = false;
//此变量可以保存点击黑色元件的位置
var point:Point=new Point();
//侦听事件
var black:MovieClip
black.addEventListener(MouseEvent.MOUSE_DOWN,handle);
stage.addEventListener(MouseEvent.MOUSE_UP,handle);
//移动事件用stage侦听,也可以侦听ENTER_FRAME事件;
stage.addEventListener(MouseEvent.MOUSE_MOVE,handle);
function handle(e:MouseEvent):void {
    if (e.type == MouseEvent.MOUSE_DOWN) {
        down = true;
        black.startDrag(false)
    } else if (e.type==MouseEvent.MOUSE_UP) {
        down = false;
        black.stopDrag()
    } else if (e.type==MouseEvent.MOUSE_MOVE) {
        if (down==true) {
            //黑色元件随鼠标移动
            trace(black.transform.pixelBounds.size)
            //black.x = mouseX 
            //限定移动范围
            //因为我不确定你的元件是怎么安排坐标的,以下这么写适合所有情况
            if (black.transform.pixelBounds.left < powder.transform.pixelBounds.left) {
                black.x =powder.x
            } else if (black.transform.pixelBounds.right>powder.transform.pixelBounds.right) {
                black.x =powder.x+powder.width-black.width
            } else if (black.transform.pixelBounds.top<powder.transform.pixelBounds.top) {
                black.y=powder.y
            }else if (black.transform.pixelBounds.bottom>powder.transform.pixelBounds.bottom) {
                black.y=powder.y+powder.height-black.height
            }
        }
    }
}

 

posted on 2019-08-21 17:26  zqiang0803  阅读(540)  评论(0编辑  收藏  举报

导航