将事件侦听器添加到在AS3中执行拖放功能的数组

时间:2011-03-21 18:32:33

标签: flash actionscript-3 flash-cs5

这是我第一次真正的编程工作,这是让我的小项目成功的最后一件事。

我使用此代码的目的是将事件侦听器添加到将在舞台上拖放它们的Movie Clips数组中。

以下是代码:

var itemBank:Array = new Array(d1_anim.drawer1.test01.movieClip_1, d1_anim.drawer1.test01.movieClip_2);

for(var i:int = 0; i < itemBank.length; i++) {
    itemBank[i].buttonMode = true;
    itemBank[i].addEventListener(MouseEvent.MOUSE_DOWN, pickUp);
    itemBank[i].addEventListener(MouseEvent.MOUSE_UP, dropOff);
    trace("pickUp added to " + itemBank[i]);
}

function pickUp(event:MouseEvent):void
{
    event.target.startDrag(true);
    trace("Draging " + event.target);
}

现在MC没有拖动,跟踪声明说:

  

pickUp添加到[object MovieClip]

编辑: 这是我的fla,我放弃了。我不知道为什么它不会工作。请帮忙。 [在此下载](编辑:删除下载链接)

1 个答案:

答案 0 :(得分:2)

您当前的代码已经过测试并且运行正常。错误必须在其他地方。

如果您需要我使用的测试代码,您可以在此处下载源代码:Drag & Drop Source File(与您的代码相同,这只是证明它有效)。


编辑:以下是我对您的代码所做的更改,以使其正常工作。阅读评论以便更好地理解。我还将d1_anim.drawer1.test01.hair1影片剪辑的注册点更改为居中而不是左上角,这是使其工作所必需的。

import flash.display.MovieClip;
import com.reintroducing.ui.SliderUI; // Always have imports at top. It's a good practice.

var itemBank:Array = new Array(d1_anim.drawer1.test01.hair1);

for(var i:int = 0; i < itemBank.length; i++) {
    itemBank[i].buttonMode = true;
    itemBank[i].mouseChildren = false;// Added this line. For explanation go to: http://ryanbosinger.com/blog/2008/actionscript-3-eventtarget-returns-children-of-movieclip/
    itemBank[i].addEventListener(MouseEvent.MOUSE_DOWN, pickUp);
    itemBank[i].addEventListener(MouseEvent.MOUSE_UP, dropOff);
    trace("pickUp added to " + itemBank[i]);
}

function pickUp(e:MouseEvent):void
{
    e.currentTarget.startDrag(true);
    trace("Draging " + e.currentTarget);
}
function dropOff(e:MouseEvent):void
{
    // --- Change 'this' to 'e.currentTarget' --- \\
    e.currentTarget.stopDrag();
    e.currentTarget.x = mouseX;
    e.currentTarget.y = mouseY;
    e.currentTarget.width = 200;
    // --- Putting the target in a temporary variable made an error dissapear. --- \\
    // --- I don't really know why and i don't really care either --- \\
    var tempMC = e.currentTarget;
    this.stage.addChild(tempMC);
    d1_anim.visible = false;
}

And here is a link to the working .fla