如何检查多个符号的碰撞

时间:2016-03-16 15:52:16

标签: actionscript-3 flash

我想知道是否可以通过实例名称检查碰撞,而不是单独的mc名称。我有大约150-200个对象(pacman游戏的点),我需要检查碰撞,并希望有效地做到这一点。谢谢!

1 个答案:

答案 0 :(得分:2)

如果你有一个名为dots的实例和一个播放器,你可以这样做:

//a var to hold each loop iteration's dot for convenience
var tmpDot:DisplayObject;

//loop 200 times from 1 - 200
for(var i:int=1;i<= 200;i++){
    //getChildByName gets an instance from a string, in this case dot plus i (i is the current iteration number)
    tmpDot = getChildByName("dot" + i);

    //check if the dot exists and is hitting the player
    if(tmpDot && tmpDot.hitTestObject(player)){
        //hit a dot, do something here like remove the dot
        removeChild(tmpDot);
        //increment points etc.

        //if there's no possibility of the player hitting more than one dot at a time, then for efficiency you should break out of this loop
        break;
    }
}

现在,正如您对问题的评论中所提到的,给出200个点实例名称是乏味的。一种更简单的方法是将你的dot MovieClip放在你的库中,转到它的属性,并将其导出为actionscript(假设你给它一个类名为Dot)。然后你可以做的是,在一个关卡的开头找到你在时间轴上的所有点对象(不需要实例名称)并将它们添加到一个数组中:

//DO THIS ONLY WHEN THE LEVEL STARTS

//create a vector/array to store all your dots for better speed
var allDots:Vector.<Dot> = new Vector.<Dot>();

//iterate over all the children of this timeline frame
for(var i:int=0;i<numChildren;i++){
    //if the item is a Dot, add it to the array
    if(getChildAt(i) is Dot){
        allDots.push(getChildAt(i) as Dot);
    }
}

现在,您可以执行以下命中测试:

//YOU PROBABLY WANT TO DO THIS EITHER EVERY FRAME, OR WHENEVER THE PLAYER MOVES

//flag to see if all dots are eaten
var allEaten:Boolean = true;
var tmpDot:Dot;

for(var i:int=0;i<allDots.length;i++){
    tmpDot = allDots[i];

    //.... same as the top code example at this point
    if(tmpDot && tmpDot.hitTestObject(player)){
        removeChild(tmpDot);
        //do anything else you need to do when a dot is eaten

        //if we've already determined that we haven't eaten all the dots, then break the loop
        if(!allEaten) break;
    }

    //if a dot has a parent, then they haven't been all eaten
    if(tmpDot.parent){
        allEaten = false;
    }
}