AS3:如何为可拖动对象定义边界?

时间:2011-05-18 05:35:58

标签: flash actionscript-3

我正在闪光灯中制作一个图像启示器,但我无法绕过如何将滑块约束到area_mc。主要在mouseMoveHandler。有人可以给我一些指示吗?

import com.greensock.*;
import com.greensock.easing.*;

function init():void  {
    area_mc.sliderbar_mc.buttonMode = true;
    area_mc.sliderbar_mc.addEventListener(MouseEvent.MOUSE_DOWN,moveSliderbar);
    stage.addEventListener(MouseEvent.MOUSE_UP,stopSliderbar);
    area_mc.mask_mc.alpha = 0;
    area_mc.after_mc.mask = area_mc.mask_mc;
    TweenLite.to(area_mc.sliderbar_mc,3,{x:stage.stageWidth/2,ease:Elastic.easeOut});
    TweenLite.to(area_mc.mask_mc,3,{x:stage.stageWidth/2,ease:Elastic.easeOut});
}  

function moveSliderbar(event:MouseEvent):void {
    stage.addEventListener(MouseEvent.MOUSE_MOVE,mouseMoveHandler);
}  

function stopSliderbar(event:MouseEvent):void {
    stage.removeEventListener(MouseEvent.MOUSE_MOVE,mouseMoveHandler);
}

function mouseMoveHandler(event:MouseEvent):void {
    area_mc.sliderbar_mc.x = area_mc.mouseX;
    var left:Number = area_mc.x - (area_mc.width / 2);
    var right:Number = area_mc.x + (area_mc.width / 2);

    if (area_mc.sliderbar_mc.x > right) {
        area_mc.sliderbar_mc.x = right;
    }
    else if(area_mc.sliderbar_mc.x < left){
        area_mc.sliderbar_mc.x = left;
    }
    area_mc.mask_mc.x = area_mc.sliderbar_mc.x;
}

init();

1 个答案:

答案 0 :(得分:6)

基于我将您的问题解释为:“我如何提供可拖动的项目边界?”。

startDrag()有一个接受Rectangleflash.geom.Rectangle)的参数,该参数将作为您可以拖动某些内容的边界。

例如

var rect:Rectangle = new Rectangle(0,0,100,100);
startDrag(false, rect);

这是我如何做一个你拖动和限制的对象:

package
{
    import flash.display.MovieClip;
    import flash.geom.Rectangle;
    import flash.events.MouseEvent;

    public class DragableItem extends MovieClip
    {
        // vars
        private var _boundaries:Rectangle;

        /**
         * Constructor
         */
        public function DragableItem()
        {
            // define boundaries
            // left, top, right, bottom
            _boundaries = new Rectangle(30,30,200,200);

            addEventListener(MouseEvent.MOUSE_DOWN, _mouseDown);
        }

        /**
         * MOUSE_DOWN
         */
        private function _mouseDown(e:MouseEvent):void
        {
            startDrag(false, _boundaries);

            addEventListener(MouseEvent.MOUSE_UP, _stopDrag);
            addEventListener(MouseEvent.MOUSE_OUT, _stopDrag);
        }

        /**
         * MOUSE_UP
         */
        private function _stopDrag(e:MouseEvent):void
        {
            stopDrag();

            removeEventListener(MouseEvent.MOUSE_UP, _stopDrag);
            removeEventListener(MouseEvent.MOUSE_OUT, _stopDrag);
        }
    }
}

快速测试:

var drg:DragableItem = new DragableItem();

drg.graphics.beginFill(0);
drg.graphics.drawRect(0,0,60,60);
drg.graphics.endFill();

addChild(drg);