Actionscript 3 - 如何使新实例可拖动?

Actionscript 3 - How do I make new instances draggable?

我正在尝试构建一个拖放游戏,用户可以在其中使用我提供的图像构建一些东西。我将在菜单中包含图像,用户可以单击并拖动到建筑区域。用户将能够根据需要添加该图像的任意多个实例。

我能够让它的一部分工作。到目前为止,我可以单击图像并将其四处拖动,并根据需要创建任意数量的实例。但是,我无法在放置图像后单击并拖动它。

当我跟踪查看名称时,它说所有新实例都被命名为 hillChild1。我试图将它们命名为 hillChild1、hillChild2 等,但这似乎也不起作用……不过不确定这是不是一个问题。

这是我的代码:

thesubmenu1.hill.addEventListener(MouseEvent.MOUSE_DOWN, onDown);
stage.addEventListener(MouseEvent.MOUSE_UP, onUp);

var myImage:Sprite = Sprite(new Hill_mc());
var i:Number=0; i++;


function onDown(e:MouseEvent):void {
    var myImage:Sprite = Sprite(new Hill_mc());
    myImage.name = "hillChild"+i;
    addChild(myImage);
    myImage.x = mouseX;
    myImage.y = mouseY;
    myImage.startDrag();
    myImage.buttonMode = true;
}
function onUp(e:MouseEvent):void {
    var myImage:Sprite = Sprite(new Hill_mc());
    myImage.stopDrag();
    myImage.name = "hillChild";
}



stage.addEventListener(MouseEvent.CLICK, traceName);
function traceName(event:MouseEvent):void { trace(event.target.name); }



myImage.getChild(myImage).addEventListener("mouseDown", mouseDownHandler);
stage.addEventListener("mouseUp", mouseUpHandler);

function mouseDownHandler (e:MouseEvent):void{
   myImage.startDrag();
}
function mouseUpHandler (e:MouseEvent):void{
   myImage.stopDrag();
}

我是 Whosebug 和 Actionscript 3 的新手,如果不是很明显的话。

您的问题可能是您在松开鼠标时创建了一个新实例(当您想要的是对已在按下鼠标时创建的实例的引用)。此外,您永远不会向新对象添加点击监听器。仅在鼠标按下后将鼠标弹起监听器添加到舞台(然后移除鼠标弹起时的监听器)。

thesubmenu1.hill.addEventListener(MouseEvent.MOUSE_DOWN, createCopy);

var i:int=0;
var tmpImage:Sprite; //to store which image is being dragged currently

function createCopy(e:MouseEvent):void {
    tmpImage = new Hill_mc();
    tmpImage.name = "hillChild"+(i++); //increment every copy
    addChild(tmpImage);
    tmpImage.x = mouseX;
    tmpImage.y = mouseY;
    tmpImage.startDrag();
    tmpImage.buttonMode = true;
    tmpImage.addEventListener(MouseEvent.MOUSE_DOWN, onDown); //add the mouse down to this new object
    stage.addEventListener(MouseEvent.MOUSE_UP, onUp); //since the mouse is currently down, we need to listen for mouse up to tell the current copy to stop dragging
}

//this will be called when click a copy
function onDown(e:MouseEvent):void {
    tmpImage = Sprite(e.currentTarget); //get a reference to the one that was clicked, so we know which object to stop dragging on the global mouse up.
    stage.addEventListener(MouseEvent.MOUSE_UP, onUp); //listen for the mouse up
    tmpImage.startDrag();
}
function onUp(e:MouseEvent):void {
    stage.removeEventListener(MouseEvent.MOUSE_UP,onUp); //now that the mouse is released, stop listening for mouse up
    tmpImage.stopDrag(); //stop dragging the one that was clicked
}