我有这个AS3代码:
circle_mc.addEventListener(MouseEvent.MOUSE_DOWN, drag);
square_mc.addEventListener(MouseEvent.MOUSE_DOWN, drag);
stage.addEventListener(MouseEvent.MOUSE_UP, drop);
function drag(e:MouseEvent):void
{
e.target.startDrag(false, new Rectangle(30,30,150,150));
}
function drop(e:MouseEvent):void
{
stopDrag();
}
现在,如果我测试电影,如果我点击圆圈或正方形,它们会跳到舞台上,因为我不允许将它们移出那个矩形。
我希望脚本允许我在任何地方拖动形状(当MOUSE_DOWN事件处于活动状态时),但仍然不允许我将它们从它中删除(在MOUSE_UP上)。
如何使用对象代替该矩形阶段?
答案 0 :(得分:1)
创建一个名为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;
}
}
答案 1 :(得分:0)
嘿,我遇到了这段代码。从
改变不是更好 if (target_mc.hitTestPoint(stage.mouseX,stage.mouseY,true))
{
trace("it was dropped INSIDE the target area");
// ...
}
要
if (target_mc.hitTestPoint(draggedObject.x,draggedObject.y,true))
{
trace("it was dropped INSIDE the target area");
// ...
}
如果您单击鼠标,第一个将触发代码,即使您没有拖动对象。 最后一个将确保拖动的对象击中目标,而不是确保鼠标是。