as3 对象数组 - 以恒定速度运动

as3 array of objects - movement with constant speed

好的,我对 as3 有一些经验和一些基础知识。但是这个问题困扰了我很久。我试图根据我目前对 as3 的了解来做一个解决方法。但不知何故,要么我收到一条错误消息,要么它根本不做任何事情。这是我要解决的代码。

    var zombieCount:Array = new Array();

    var helltime:Timer = new Timer(1500);
    helltime.addEventListener(TimerEvent.TIMER, spawnzombies)



    helltime.start();
    function spawnzombies(happened:TimerEvent){
        var zombie1:Zombie = new Zombie();
        zombieCount.push(zombie1);
        stage.addChild(zombieCount[zombieCount.length - 1]);
        zombie1.x = 135 + (330*Math.random())
        zombie1.y = -29


        stage.addEventListener(Event.ENTER_FRAME, move_zombie)

        function move_zombie(happened:Event){
            for(var i:int; i < zombieCount.length; i++){
                zombieCount[i].y = zombieCount[i].y + 1;
                if(zombieCount[i].hitTestObject(border)){
                    stage.removeChild(zombieCount[i]);
                    zombieCount.shift();
                    trace(zombieCount.length);
                }

            }



        }
    }

虽然这可能不包括所有错误,但这里至少是我看到的一些问题。

  1. 内联函数问题:

    在您的计时器滴答处理程序 (spawnZombies) 中,您创建了一个名为 move_zombie 的内联函数,然后添加了一个调用该函数的输入帧处理程序。

    这里的问题是,计时器的每个滴答声都会创建该函数的全新副本,并添加另一个进入帧处理程序。这将在几个计时器滴答后产生巨大的问题。

    spawn 函数之外打破 move_zombie 函数:

    例如:

    helltime.addEventListener(TimerEvent.TIMER, spawnzombies)
    helltime.start();
    
    stage.addEventListener(Event.ENTER_FRAME, move_zombie);
    
    function move_zombie(......
    
    function spawnzombies(.....
    
  2. 迭代问题:

    在你的 for 循环中:

        for(var i:int; i < zombieCount.length; i++){
            zombieCount[i].y = zombieCount[i].y + 1;
            if(zombieCount[i].hitTestObject(border)){
                stage.removeChild(zombieCount[i]);
                zombieCount.shift();
                trace(zombieCount.length);
            }
        }
    

    您没有初始化 i 值。虽然这会将其默认为 0,但为了可读性对其进行初始化仍然是一个好主意。

    所以你从 0 向前迭代到数组的末尾。但是,如果命中测试成功,则可以使用数组的 shift 方法。这将删除数组的 first 项(无论当时 i 的值是多少)。这将删除错误的项目,加上弄乱 zombieCount[i] 所指的内容(因为在进行移位后项目的数量现在已经改变,所以下一次迭代 zombieCount[i] 将引用与前一次相同的项目迭代)。

    使用 splice 方法删除并向后迭代,这样您的索引就不会乱七八糟。

    for(var i:int=zombieCount.length-1;i >=0;i--){
        zombieCount[i].y += 1; //move it down 1 pixel
        if(zombieCount[i].hitTestObject(border)){
            stage.removeChild(zombieCount[i]);
            zombieCount.splice(i,1); //remove the item at the current index (do this instead of shift)
            trace(zombieCount.length);
        }
    }