AS3 - array hit test in 'for each' loop only works properly with last object in array

给你一囗甜甜゛ 提交于 2019-12-13 05:50:57

问题


I'm trying to build a platform game in AS3 by placing all instances of my Platform class into an Array, then running a for each loop with a hitTestObject to check whether the player is touching any of them.

My problem is that whilst the player will react correctly to touching each of the platforms in the Array (i.e. stop falling and set y position to the top of the platform), I can only perform the jump function whilst standing on the last Platform in the Array.

I'm fairly new to ActionScript so I have no idea why this is happening - surely the 'for each' loop means that each platform should act in the same way? Some of the code certainly works for each platform, but for some reason not that which allows the player to jump.

If anyone knows why this is happening and can provide a solution, I would be very grateful. This has been driving me up the wall for several days now.

Here's the relevant code. The function is called on an enter frame listener.

private function collisionTestPlatforms (event:Event) : void {
        for each (var i:Platform in aPlatforms) {
            if (player.hitTestObject(i)) {
                Player.touchingGround = true;
                player.y = i.y - 25;
                Player.yVelocity = 0;
            } else {
                Player.touchingGround = false;
            }
        }
    }

Thank you very much!


回答1:


Similar to @DodgerThud's suggestion, you could take the conditional else out of the loop:

private function collisionTestPlatforms (event:Event) : void {
    //By default, the player is not touching the ground until we find 
    // a collision with one of the platforms
    Player.touchingGround = false;
    for each (var i:Platform in aPlatforms) {
        if (player.hitTestObject(i)) {
            Player.touchingGround = true;
            player.y = i.y - 25;
            Player.yVelocity = 0;
        }
    }
}


来源:https://stackoverflow.com/questions/37700932/as3-array-hit-test-in-for-each-loop-only-works-properly-with-last-object-in

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!