当两个实例发生碰撞时如何添加Child?

时间:2012-10-02 04:12:08

标签: actionscript-3 collision

我正在尝试创建虚拟生活模拟,当男孩鱼和女孩鱼相撞时,它们会重现。这是我第一次使用外部类文件,我很困惑。

package {

import flash.display.MovieClip;
import flash.events.Event;

public class Main extends MovieClip
{
    var numBalls:Number = 3;
    var bFishList:Array = new Array();
    var gFishList:Array = new Array();

    public static var bFish:BoyFish = new BoyFish  ;
    public static var gFish:GirlFish = new GirlFish  ;
    var fishName:Object = bFish.name;

    public function Main()
    {
        addEventListener(Event.ADDED_TO_STAGE, enterFrameNow);
        function enterFrameNow(event:Event):void {
            // constructor code
            for (var i = 0; i < numBalls; i++) {
                var bFish:MovieClip = new BoyFish();
                bFish.name = "bFish"+i;
                addChild(bFish);

                //variable ball a movieclip is a new instance of Ball

                var gFish:MovieClip = new GirlFish();
                // ball x and y value was in the middle of the stage
                bFish.x = stage.stageWidth / 2;
                bFish.y = stage.stageHeight / 2;
                // add ball to stage

                bFishList.push(bFish);

                // ball x and y value was in the middle of the stage
                gFish.x = stage.stageWidth / 2;
                gFish.y = stage.stageHeight / 2;

                // add ball to stage
                addChild(gFish);
                gFishList.push(gFish);

                addEventListener(Event.ENTER_FRAME, hitTest);
                function hitTest(event:Event):void {
                    for (i = 0; i < bFishList.length; i++) {
                        if (gFish.hitTestObject(bFishList[i]) == true) {
                            addChild(gFish);
                            gFishList.push(gFish);
                            trace("hit");
                        }
                    }
                }
            }

        }
        trace(bFishList);
        trace(gFishList);
    }

}
}

这是我的Main.as文件中的代码。我已经尝试了hitTestObject这件事,并且这对我不起作用。

任何人都可以帮助我吗?我希望它在bFishgFish发生碰撞时向舞台添加另一个实例。

1 个答案:

答案 0 :(得分:0)

你不应该添加那么多的enterFrame事件。

在您的类中只添加一个enterFrame处理程序,而不是作为本地函数,并在其中添加嵌套循环。

//Somewhere in your Main() function :
addEventListener(Event.ENTER_FRAME, this.hitTest);

//In class Main
public function hitTest(event:Event):void
{
    for (var i = 0; i < bFishList.length; i++)
    {
        for (var j = 0; j < gFishList.length; j++)
        {
            if (gFishList[j].hitTestObject(bFishList[i]))
            {
                var newFish:MovieClip = new GirlFish(); //Create it.
                addChild(newFish);
                gFishList.push(newFish);
            }
        }
    }
}

请注意,如果您不再采取任何行动,可能会导致每帧产生许多女孩鱼,最终可能会冻结Flashplayer。