2014-02-22 23 views
0

我有一个由定时器事件添加到舞台的影片剪辑数组。这个影片剪辑被称为mSquare。现在我想为影片剪辑设置一个EventListener,所以无论何时用户点击影片剪辑,然后它被破坏,但我有麻烦设置它,因为它们有一个数组添加到舞台。 我不断收到此错误:如何MouseEvent.Click在数组中的多个影片剪辑

Cannot access a property or method of a null object reference.

这是我走到这一步:

mSquare.addEventListener(MouseEvent.CLICK, mIsDown); 
mIsDown功能,我知道我必须去通过阵列,所以我试图建立一些

现在像这样:

private function mIsDown(e:MouseEvent):void 
{  
    for (var i:int = 0; i < aSquareArray.length; i++) 
    { 
     //Get current Square in i loop 
     var currentSquare:mcSquare = aSquareArray[i]; 

     if ( ) 
     { 
      trace(currentSquare + "Mouse Is Down"); 
     } 
    } 
} 

而且,这里是我的广场是如何添加到舞台:

private function addSquare(e:TimerEvent):void 
{ 
    mSquare = new mcSquare(); 
    stage.addChildAt(mSquare, 0); 
    mSquare.x = (stage.stageWidth/2); 
    mSquare.y = (stage.stageHeight/2) + 450; 

    aSquareArray.push(mSquare); 
    // trace(aSquareArray.length); 
} 

任何帮助将不胜感激我需要做的,以便用户能够MOUSE.click或MouseDown的电影剪辑数组谢谢!

** * ** * ** * ** * ** * *下面是我在做,现在* * ** * ** * ** * ****

stage.addEventListener(MouseEvent.MOUSE_DOWN, movieClipHandler); 

private function movieClipHandler(e:MouseEvent):void //test 
    { 
     mouseIsDown = true; 
     mSquare.addEventListener(MouseEvent.MOUSE_DOWN, squareIsBeingClicked); 
    } 

private function squareIsBeingClicked(e:MouseEvent):void 
    { 

     var square:DisplayObject = e.target as DisplayObject; // HERE is your clicked square 
     var i:int = aSquareArray.indexOf(square); // and HERE is your index in the array 

     if (i < 0) 
     { 
      // the MC is out of the array 
       trace("Clicked"); 
       checkSquareIsClicked(); 


     } else 
     { 
      // the MC is in the array 

     } 


    } 


    private function checkSquareIsClicked():void 
    { 


     for (var i:int = 0; i < aSquareArray.length; i++) 
     { 

      var currentSquare:mcSquare = aSquareArray[i]; 

      if (mouseIsDown) 
      { 
       aSquareArray.splice(i, 1); 
       currentSquare.destroySquare(); 
       nLives --; 
       mouseIsDown = false; 

      } 

     } 
    } 

回答

1

最简单的答案是使用传入侦听器的事件的target属性。通过这种方式,您不需要遍历数组以找到MC被点击的位置,就可以将其作为目标并继续。要获得阵列中目标MC的位置,请调用indexOf函数。

private function mIsDown(e:MouseEvent):void 
{ 
    var mc:DisplayObject = e.target as DisplayObject; // HERE is your clicked square 
    var i:int=aSquareArray.indexOf(mc); // and HERE is your index in the array 
    if (i<0) { 
     // the MC is out of the array 
    } else { 
     // the MC is in the array 
    } 
} 
+0

好吧,这是有道理的。我正在试图用昨晚的目标做一些事情,但没有想到这个指数。有点新鲜。所以我必须将我的鼠标EventListener更改为stage.addevent?或者将它保留为mSquare.addeventListener,因为每当我测试电影时,我都会在该特定行上得到错误:无法访问空对象引用的属性或方法。 – Nathan

+0

那么我加了mSquare = new mcSquare();在我的构造函数中,错误消失了。仍然似乎不能得到对mIsDown函数的追踪。啊! – Nathan

+0

只是主要混淆了if语句?我将如何使用它来检查广场对象是否被点击? – Nathan