我正在尝试构建一个拖放游戏,用户可以使用我提供的图像构建一些东西。我将在菜单中显示用户可以单击并拖动到建筑区域的图像。用户将能够根据需要添加该图像的多个实例。
我能够让它的一部分工作。到目前为止,我可以单击图像并将其拖动,然后根据需要创建尽可能多的实例。但是,我放置后无法点击并拖动图片。
当我进行跟踪以查看名称时,它表示所有新实例都名为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();
}
我不熟悉StackOverflow以及Actionscript 3,如果它不明显的话。
答案 0 :(得分:0)
您的问题可能是您在鼠标上创建新实例(当您想要的是对已经在鼠标按下时创建的实例的引用)。此外,您永远不会向新对象添加单击侦听器。只有在鼠标按下后才能将鼠标向上侦听器添加到舞台上(然后在鼠标中删除侦听器)。
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
}