AS3如何在不复制和粘贴代码的情况下将多个子项添加到阶段

时间:2014-10-23 16:01:59

标签: actionscript-3

每次运行程序时,我都会在舞台上添加1个牛仔。当我运行程序时,我希望舞台上有5个牛仔。我知道我可以复制并粘贴代码4次,但我想知道是否有更短更快的方法来做到这一点。

这是我的代码

package 
{
    import flash.display.Sprite;
    import flash.events.Event;
    import flash.display.Bitmap;
    import flash.ui.Mouse;
    import flash.events.MouseEvent;

    /**
     * ...
     * @author Callum Singh
     */
    public class Main extends Sprite 
    {
        public var gun:crosshair;
        public var cowboy:enemy;

        public function Main():void 
        {
            if (stage) init();
            else addEventListener(Event.ADDED_TO_STAGE, init);
        }

        private function init(e:Event = null):void 
        {
            removeEventListener(Event.ADDED_TO_STAGE, init);

            gun = new crosshair();
            stage.addChild (gun);
            addEventListener(Event.ENTER_FRAME, moveCrosshair);

            cowboy = new enemy();
            cowboy.x = Math.random() * 600;
            cowboy.y = Math.random() * 400;
            stage.addChild(cowboy);
            cowboy.addEventListener(MouseEvent.CLICK, handleShoot);

        }

        private function moveCrosshair(e:Event):void
        {
            gun.x = mouseX -120;
            gun.y = mouseY -115;
            Mouse.hide();

        }

        private function handleShoot(e:MouseEvent):void
        {
            if (e.target == cowboy)
                {
                    cowboy.visible = false;
                }   
        }

    }

}

2 个答案:

答案 0 :(得分:1)

基本for循环应该可以解决问题。

for(var i:uint = 0; i < 5; ++i) {
    cowboy = new enemy();
    cowboy.x = Math.random() * 600;
    cowboy.y = Math.random() * 400;
    stage.addChild(cowboy);
    cowboy.addEventListener(MouseEvent.CLICK, handleShoot);
}

答案 1 :(得分:1)

虽然Iggy是正确的,但根据您的其余代码,它将无法正常工作。如果单独留下,它仍然会得到5个牛仔但只创造1个牛仔参考。 cowboy是一个类变量,执行他的代码只会在每次循环时覆盖cowboy变量。

你需要抓住每个牛仔实例。基本方法是将它们存储到Array或Vector中。您也可以按名称引用它们(如果您正在设置它)。从上面获取代码,这里只考虑两个选项的调整。

    public class Main extends Sprite 
    {
        public var gun:crosshair;
        public var cowboys:Array;  // Array to hold all your cowboys

        private function init(e:Event = null):void 
        {
            removeEventListener(Event.ADDED_TO_STAGE, init);

            gun = new crosshair();
            stage.addChild (gun);
            addEventListener(Event.ENTER_FRAME, moveCrosshair);

            cowboys = new Array();

            for(var i:uint = 0; i < 5; ++i) {
                var cowboy:enemy = new enemy();
                cowboy.x = Math.random() * 600;
                cowboy.y = Math.random() * 400;
                cowboy.name = "cowboy" + i; // assuming that your enemy class extends DisplayObject types
                stage.addChild(cowboy);
                cowboy.addEventListener(MouseEvent.CLICK, handleShoot);
                cowboys.push(cowboy);
            }
        }