0

我有一个电影剪辑,在那个电影剪辑中还有一些电影剪辑(矩形)......我如何检测与所有这些矩形的碰撞而不必为每个矩形编写代码?

4

1 回答 1

1

您可以像这样迭代任何 DisplayObjectContainer 的子项:

for( var i:int = 0; i < clip.numChildren; i++) 
    doStuffWith( clip.getChildAt(i) );

要测试与任何子对象的碰撞,您可以使用以下命令:

function hitTestChildren( target:DisplayObject, parent:DisplayObjectContainer ):Boolean {
    for( var i:int = 0; i< parent.numChildren; i++)
        if( target.hitTestObject( parent.getChildAt(i))) return true;
    return false;
}

编辑

查看源 FLA 后,以下是如何在重力模拟中包含碰撞:

function hitTestY( target:DisplayObject, container:DisplayObjectContainer ):Number {
    //iterate over all the child objects of the container (i.e. the "parent")
    for( var i:int = 0; i< container.numChildren; i++) {
        var mc:DisplayObject = container.getChildAt(i)
        // Test for collisions
        // There were some glitches with Shapes, so we only test Sprites and MovieClips 
        if( mc is Sprite && target.hitTestObject( mc )) 
            // return the global y-coordinate (relative to the stage) of the object that was hit
            return container.localToGlobal( new Point(mc.x, mc.y ) ).y;
    }
    // if nothing was hit, just return the target's original y-coordinate
    return target.y;
}

function onEnter(evt:Event):void {
    vy +=  ay;
    vx +=  ax;
    vx *=  friction;
    vy *=  friction;
    ball.x +=  vx;
    ball.y +=  vy;
    ball.y = hitTestY( ball, platform_mc);
}

不过,您必须修改矩形对象,使它们各自的原点位于 0,0 而不是形状的中间。

结束编辑

但是,如果您处理的不是简单的矩形形状,而是复杂的形状或透明度,您可能需要使用不同的方法:您可以将形状的任意组合绘制到位图,然后使用BitmapData#hitTest来查看它们是否相交(在此在这种情况下,您可以对parent包含所有子项的整个文件和target剪辑本身执行此操作,但不能对单个子项执行此操作)。

我不会发布任何代码(它很长),但在Mike Chambers 的博客上有一个很好且干净的示例说明如何做到这一点。

于 2013-02-24T12:01:07.667 回答