【问题标题】:Need help looping the spawning of an object in AS3需要帮助在 AS3 中循环生成对象
【发布时间】:2016-01-22 09:53:12
【问题描述】:

对于学校,我正在为移动设备创建一个基本的 AS3 游戏,基本上你只需要知道我需要一个与舞台宽度相同的矩形 (380)(高度无关紧要),然后在顶部生成几秒钟后,另一个产生,这个过程无限重复,直到另有说明。我还没有做太多,所以我没有太多代码要展示,但如果有人能告诉我如何将不胜感激。

我已经完成了移动,只是没有产卵

var rectangle:Shape = new Shape;
var RecTimer:Timer = new Timer(10,10000);
RecTimer.addEventListener(TimerEvent.TIMER, fRecMovement);
RecTimer.start()


function fRecMovement (e:TimerEvent):void {

rectangle.graphics.beginFill(0xFF0000); // choosing the colour for the fill, here it is red
rectangle.graphics.drawRect(0, 0, 480,45.49); // (x spacing, y spacing, width, height)
rectangle.graphics.endFill();
addChild(rectangle); // adds the rectangle to the stage
rectangle.y +=1


}

【问题讨论】:

    标签: actionscript-3 flash loops spawning


    【解决方案1】:

    每次想要添加东西时,都需要使用 new 关键字创建一个新形状。但是您还需要跟踪您创建的每个矩形,以便您可以移动它。在下面的代码中,矩形数组是所有矩形的列表。然后你可以遍历列表并移动每个矩形。

    var RecTimer:Timer = new Timer(10,10000);
    RecTimer.addEventListener(TimerEvent.TIMER, onTimer);
    RecTimer.start();
    
    var rectangles:Array = []; // a list of all the rectangles we've made so far
    
    function spawnRectangle():void {
        var rectangle:Shape = new Shape();
        rectangle.graphics.beginFill(0xFF0000); // choosing the colour for the fill, here it is red
        rectangle.graphics.drawRect(0, nextRectangleY, 480, 45.49); // (x spacing, y spacing, width, height)
        rectangle.graphics.endFill();
        addChild(rectangle); // adds the rectangle to the stage
    
        rectangles.push(rectangle); // adds the rectangle to our list of rectangles
    }
    
    function moveAllRectangles():void {
        for each (var rectangle:* in rectangles) {
            rectangle.y += 1;
        }
    }
    
    function onTimer(e:TimerEvent) {
        spawnRectangle();
        moveAllRectangles();
    }
    

    这将在每次计时器运行时创建一个新矩形,但您可能希望比这慢一些。也许你可以用一个单独的计时器来做到这一点。

    另外,如果你继续让这段代码运行,它会减慢很多,并使用大量内存,因为它会不断创建新的矩形并且永不停止!看看你能不能找到一种方法来限制它。

    【讨论】:

    • 非常感谢,目前它似乎没有移动矩形,请看一下,但是非常感谢,这为我节省了很多时间!也许一个想法是在每个矩形达到某个 y 值时“删除”每个矩形?
    • 成功,我让它移动,移动循环中的微小错误,下一步是是否可以在产卵之间留出间距,因为到目前为止它是一个恒定的矩形流,你有什么想法吗?
    • 发生这种情况是因为您创建矩形太快而移动它们太慢(这就是我发布的代码中发生的情况),因此您将看不到它们之间的任何间隙。因此,您需要使矩形变慢或更快地移动它们(可能两者兼而有之)
    • 我让它工作了,现在我遇到了一个新问题(对所有这些都感到抱歉)但是过了一段时间矩形停止移动但它们继续产卵,如果它与计时器有关的话请你帮帮我。
    • @jackmrobertson - 您不会在旧问题的 cmets 中发布新问题。用新问题制作一个新问题。
    猜你喜欢
    • 1970-01-01
    • 2021-05-14
    • 2018-06-06
    • 1970-01-01
    • 1970-01-01
    • 2013-05-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多