Search code examples
actionscript-3flash-cs5flash

MovieClip Y position becomes negative on update loop using delta time


I am coding a game in flash AS3 and I have implemented my game loop using the answer provided here: Is this a good implementation of the gameloop However, after increasing my movieclip's y position by dist (dist is from speed * timeElapsed) the movieclip's y position becomes negative. I have noticed this negative value by tracing the movieclips position on each update.

See code:

public class GameWorld extends MovieClip {

    var speed:Number = 250;
    var balls:Array = [];
    private var _lastTime:Number = 0;

public function GameWorld() {
    createballs();
    this.addEventListener(Event.ENTER_FRAME, loop);
}

        public function loop(e:Event):void
        {
            var now = new Date().getTime();
            var _delta = now - _lastTime;
            _lastTime = now;
            updateGameState(_delta/1000);
        }

        public function updateGameState(timeElapsed:Number):void
        {
            var dist:Number = speed * timeElapsed;
            balls[0].y += dist;
            trace(balls[0].y);
        }

        public function createballs():void
        {
            for(var i:int = 0; i < 1; i++)
            {
                var ball:Ball  = new Ball();
                ball.y = 100;
                ball.x = 100;
                addChild(ball);
                balls.push(ball);
            }
        }

    }

I would like to know what is causing this sudden negative value of movieclips y position.


Solution

  • Yeah as @Vesper suggested, I have found the issue to be the first delta value which is very large as _lastTime is zero. The solution is to get the current time before the loop begins (before adding event listener on stage) and use that as the lastTime in the first update i.e.

    ....

        _lastTime = new Date().getTime();
        //this is the looper function called on each frame
        this.addEventListener(Event.ENTER_FRAME, _onEnterFrame);
    }
    
    public function _onEnterFrame(e:Event):void
    {
        var now = new Date().getTime();
        var _delta;
    
        _delta = now - _lastTime;
        _lastTime = now;
        updateGameState(_delta/1000);
    }
    

    This way the first _deltaTime is so small close to zero hence dist will be zero which is exactly true as the objects starting point is 0 relative to itself.