AS3:如何从基于e.target的MC数组中添加fromChild?

时间:2014-05-09 23:17:11

标签: arrays actionscript-3 drag-and-drop addchild targets

我有一个包含8个影片剪辑的数组,可以将它们拖放到MC上,这是他们常见的hitObject。

我想将任何被拖动的mc作为hitObject MC的子节点添加时被删除,但是我在设置代码时遇到了麻烦。目前,只有一个特定的实例将被添加为hitObject的子节点,因为除了特定的实例名称之外,我不知道在addChild()参数内写什么(以下都不可接受:e.target,数组名称,MovieClip名称。)

这是我的代码 - 非常感谢所有人的帮助:

import flash.events.MouseEvent;
import flash.display.MovieClip;

var redArray:Array = [red,red1,red2,red3,red4,red5,red6,red7];

redArray.forEach(setupDrag);
function setupDrag(dragger:MovieClip, index:int, array:Array):void {
    dragger.addEventListener(MouseEvent.MOUSE_DOWN, dragRed);
    dragger.buttonMode=true;}

redArray.forEach(setupDrop);
function setupDrop(dropper:MovieClip, index:int, array:Array):void {
    dropper.addEventListener(MouseEvent.MOUSE_UP, dropRed);
    dropper.buttonMode=true;}

var dirt:MovieClip

function dragRed(e:Event):void{
        dirt = e.currentTarget as MovieClip;
        e.target.startDrag();
}

function dropRed(e:Event):void{
        e.target.stopDrag();
        if (e.target.hitTestObject(drawer_mc))
        {
        drawer_mc.addChild(red1);
        red1.y=10;
        }
}

提前致谢!

2 个答案:

答案 0 :(得分:0)

你几乎就在那里。您希望将targetcurrentTarget作为参数传递给addChild。我认为以下内容应该这样做(我刚刚发布了我已经更新过的内容)。

targetcurrentTarget here之间的差异有一个很好的解释。

var dirt:MovieClip;

function dragRed(e:Event):void {
        // sounds like currentTarget and target will both work in your
        // case, but stick to one or the other for consistency
        dirt = e.currentTarget as MovieClip;
        dirt.startDrag();
}

function dropRed(e:Event):void{
        // assigning the currentTarget to your dirt variable means you don't 
        // keep needing to refer to e.currentTarget throughout the function
        dirt = e.currentTarget as MovieClip;
        dirt.stopDrag();
        if (dirt.hitTestObject(drawer_mc)) {
            // now you're always adding the instance that triggered 
            // the mouse up event
            drawer_mc.addChild(dirt);
            dirt.y=10;
        }
}

答案 1 :(得分:0)

您已经通过事件目标属性访问已删除的对象。将其转换为DisplayObject或MovieClip,然后在addChild()方法中传递它:

function dropRed(e:Event):void
{
  var droppedObject:MovieClip = e.currentTarget as MovieClip;
  droppedObject.stopDrag();

  if(droppedObject.hitTestObject(drawer_mc))
  {
    drawer_mc.addChild(droppedObject);
    droppedObject.y=10;
  }
}
  • e.target是指被点击的对象。
  • e.currentTarget是指应用了对象addEventListener() 到。