AS3将mc的startdrag约束为一个矩形,两个注册点都位于中心

时间:2012-09-13 20:47:45

标签: actionscript-3

无法想出这个。如何将注册点位于中心的mc的拖动限制为注册点位于中心的较大剪辑?下面的代码拖动名为img的剪辑,但不限制为'rect'剪辑。

var bounds:Rectangle = new Rectangle(rect.width/2-img.width/2, rect.height/2-img.height/2, rect.width-img.width, rect.height-img.height);

img.addEventListener(MouseEvent.MOUSE_DOWN, drag);
img.addEventListener(MouseEvent.MOUSE_UP, drop);

function drag(event:MouseEvent) {
    img.startDrag(false, bounds);
}
function drop(event:MouseEvent) {
    img.stopDrag();
}

2 个答案:

答案 0 :(得分:1)

如果rect是您希望对象(img)留在其中的矩形,并且它们都锚定在中心,那么这就是您所需要的:

var bounds:Rectangle = new Rectangle();
bounds.x = rect.x + (img.width * .5) - (rect.width * .5);  //offset by + half of the image, and - half of the rectangle
bounds.y = rect.y + (img.height * .5) - (rect.height * .5);
bounds.width = rect.width - img.width; //make the bounds the size of the rectangle, minus the size of the image
bounds.height = rect.height - img.height;

答案 1 :(得分:0)

注册点与拖动边界框无关。

例如

new Rectangle(0,0,100,100)

只允许MovieCLip仅从舞台最左上角的0,0移动到100,100。

[编辑]

boundingBox.graphics.moveTo(0,0);
boundingBox.graphics.beginFill(0);
boundingBox.graphics.lineTo(400,0);
boundingBox.graphics.lineTo(400,400);
boundingBox.graphics.lineTo(0,400);
boundingBox.graphics.lineTo(0,0);
boundingBox.graphics.endFill();
boundingBox.x = 100;
boundingBox.y = 100;


dragTarget.graphics.moveTo(0,0);
dragTarget.graphics.beginFill(0xff0000);
dragTarget.graphics.drawRect(0,0,10,10);
dragTarget.graphics.endFill();
dragTarget.x = 150;
dragTarget.y = 150;

container.addChild(boundingBox) 
container.addChild(dragTarget) 
this.addChild(container)

dragTarget.addEventListener(MouseEvent.MOUSE_DOWN,onDown)


var boundingBox:Sprite = new Sprite();
var dragTarget:Sprite = new Sprite();
var container:Sprite = new Sprite()
function onDown(event:Event):void{
  var bounds:Rectangle = new Rectangle(boundingBox.x,
                 boundingBox.y,
                 boundingBox.width-dragTarget.width,
                 boundingBox.height-dragTarget.height)
  dragTarget.startDrag( false,bounds )
}