0

我试图弄清楚如何在对象被拖过舞台时显示对象的 X/Y 坐标。

如果我有一个位于 0,0 的正方形并将其拖动到新位置(例如 50,50),我想在拖动时显示正方形的位置而不仅仅是在放下时。所以坐标数会随着对象的拖动而不断变化。

现在我的代码只在拖动开始和拖动停止时检测对象的 X/Y 位置:

import flash.events.MouseEvent;

this.addEventListener(MouseEvent.MOUSE_DOWN, startDragging, true);
this.addEventListener(MouseEvent.MOUSE_UP, stopDragging, true);

function startDragging(e:MouseEvent) {

square1.startDrag();
xDisplay_txt.text = square1.x;
yDisplay_txt.text = square1.y;

}

function stopDragging(e:MouseEvent) {

testStage1.stopDrag();
xDisplay_txt.text = testStage1.x;
yDisplay_txt.text = testStage1.y;

}

任何帮助表示赞赏。谢谢。

4

1 回答 1

1

您需要在拖动该东西时定期调用某个处理程序以更新输出文本。最简单的方法是使用ENTER_FRAME事件,正如其名称所述,每一帧都会触发该事件。

import flash.display.Sprite;

import flash.events.Event;
import flash.events.MouseEvent;

// We may drag different objects, we need to know which one.
var currentDrag:Sprite;

// A list of objects we can drag.
var aList:Array = [square1, square2];

// Iterate over all the items in the list
// and subscribe to each one separately.
for each (anItem:Sprite in aList)
{
    anItem.addEventListener(MouseEvent.MOUSE_DOWN, onStart);
}

function onStart(e:MouseEvent):void
{
    // Store, which one object is being dragged.
    // Read on difference between Event.target and Event.currentTarget.
    currentDrag = e.currentTarget as Sprite;
    currentDrag.startDrag();

    // Subscribe to ENTER_FRAME event to control the way of things.
    // We need to do it only if we drag square1, as requested.
    if (currentDrag == square1)
    {
        addEventListener(Event.ENTER_FRAME, onFrame);
    }

    // Subscribe to stage, because this way you will handle the
    // MOUSE_UP event even if you release the mouse somewhere outside.
    stage.addEventListener(MouseEvent.MOUSE_UP, onStop);
}

function onFrame(e:Event):void
{
    // This event fires every frame, basically, every 40 ms.
    // Round the coordinates and update the texts.
    xDisplay_txt.text = int(currentDrag.x).toString();
    yDisplay_txt.text = int(currentDrag.y).toString();
}

function onStop(e:MouseEvent):void
{
    // That is also why we are keeping the refference
    // to the object we are dragging: to know which one to drop.
    currentDrag.stopDrag();

    // We're not dragging anything anymore.
    currentDrag = null;

    // Unsubscribe, as it is no longer needed.
    // That's fine even if we didn't subscribed to in in the first place.
    removeEventListener(Event.ENTER_FRAME, onFrame);

    // Unsubscribe from this one too.
    stage.removeEventListener(MouseEvent.MOUSE_UP, onStop);
}
于 2019-12-20T20:39:44.463 回答