0

我有这个 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();
}

现在,如果我测试电影,如果我单击圆形或正方形,它们会跳到舞台上,因为我不允许将它们移出那个矩形。

  1. 我希望脚本允许我将形状拖动到任何地方(当 MOUSE_DOWN 事件处于活动状态时),但仍然不允许我将它们从其中删除(在 MOUSE_UP 上)。

  2. 我怎样才能使用一个对象而不是那个矩形舞台?

4

2 回答 2

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;
    }
}
于 2013-11-08T17:20:16.020 回答
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");
        // ...
    }

第一个,如果你用鼠标点击,将触发代码,即使你没有拖动对象。最后一个将确保拖动的对象击中目标,而不是确保鼠标击中。

于 2014-03-13T14:52:43.417 回答