[我试图弄清楚如何在将对象拖到舞台上时显示对象的X / Y坐标。
如果我有一个位于0,0的正方形,然后将其拖动到新位置,例如50,50,我想显示正方形的位置as,而不是仅在拖动时下降。因此,随着对象的拖动,坐标号将不断变化。
现在,我的代码仅在开始拖动和停止拖动时才检测到对象的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;
}
感谢您的帮助。谢谢。
您在拖动事物时需要定期调用某个处理程序,以更新输出文本。最简单的方法是使用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);
}