制作一个名为 的影片剪辑target_mc
,在其中绘制一个 150x150 的矩形,并将其放置在舞台上 x=30 和 y=30 处(这将替换代码中的矩形new Rectangle(30,30,150,150)
)。现在试试这个代码,如果它没有放在正确的位置,它会将拖动的对象恢复到原来的位置。您可以使用任何其他具有任何形状的对象来限制可放置区域。
circle_mc.addEventListener(MouseEvent.MOUSE_DOWN, drag);
square_mc.addEventListener(MouseEvent.MOUSE_DOWN, drag);
stage.addEventListener(MouseEvent.MOUSE_UP, drop);
var draggedObject:Object;
function drag(e:MouseEvent):void
{
draggedObject = e.target;
draggedObject.orginalX = draggedObject.x;
draggedObject.orginalY = draggedObject.y;
draggedObject.startDrag(false);
}
function drop(e:MouseEvent):void
{
stopDrag();
// target_mc is the name of the object you want to allow dropping over it only,
// it can be a movieclip with any shape inside it (rectangle or any other irregular shape).
// if you like you can make it invisible by setting its alpha to 0 (target_mc.alpha = 0;)
// Check if the mouse is over the target object at the dropping moment :
if (target_mc.hitTestPoint(stage.mouseX,stage.mouseY,true))
{
trace("it was dropped INSIDE the target area");
// ...
}
else
{
trace("it wa dropped OUTSIDE the target area");
// bring the dragged movie back to its orginal place,
// so it will not be able to be dropped outside your target area :
draggedObject.x = draggedObject.orginalX;
draggedObject.y = draggedObject.orginalY;
}
}