1

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

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但它对我不起作用。

谁能帮我?bFish我希望它在 a和 agFish碰撞时向舞台添加另一个实例。

4

1 回答 1

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。

于 2012-10-02T09:24:48.297 回答