我有一组电影剪辑,它们通过计时器事件添加到舞台上。这个影片剪辑被称为mSquare
。现在我想为影片剪辑设置EventListener
,所以每当用户点击影片剪辑然后它就被销毁了,但是我在设置它时遇到了麻烦有一个阵列添加到舞台上。
我一直收到这个错误:
无法访问空对象引用的属性或方法。
这是我到目前为止所得到的:
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");
}
}
}
此处还有我的Square加入舞台的方式:
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;
}
}
}
答案 0 :(得分: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
}
}