Take the 2-minute tour ×
Game Development Stack Exchange is a question and answer site for professional and independent game developers. It's 100% free, no registration required.

I am using the following game loop for my pacman clone:

long prevTime = System.currentTimeMillis();
        while (running) {
            long curTime = System.currentTimeMillis();
            float frameTime = (curTime - prevTime) / 1000f;
            prevTime = curTime;

            while (frameTime > 0.0f) {
                final float deltaTime = Math.min(frameTime, TIME_STEP);
                update(deltaTime);
                frameTime -= deltaTime;
            }

            repaint();
        }

The thing is, I don't always get the same ghost movement every time I run the game (their logic is deterministic), so it must be the game loop. I imagine it's due to the final float deltaTime = Math.min(frameTime, TIME_STEP); line. What's the best way of modifying this to perform the exact same way every time I run it? Also, any further improvements I can make?

share|improve this question
1  
What do you mean by the ghost movement not being the same every time - in specific frame or it just goes on different path? In first case it's because you base your logic on time instead of number of frames rendered so far, and in second case it's some problem in update method. –  Markus von Broady Nov 4 '12 at 19:02

1 Answer 1

What you need to do is use a fixed time step. http://gafferongames.com/game-physics/fix-your-timestep/ has some more details - it looks like you used the loop from before the 'free the physics' section. What you want is one that only updates with a fixed time step. Here's roughly what you should end up with (without spiral of death handling or interpolation):

    while (running) {
        long curTime = System.currentTimeMillis();
        float frameTime = (curTime - prevTime) / 1000f;

        while (frameTime > TIME_STEP) {
            update(TIME_STEP);
            frameTime -= TIME_STEP;
            prevTime = curTime;
        }

        repaint();
    }
share|improve this answer
    
Absolutely right! Thanks, I'll reread the article. Also, would you recommend Sytem.nanoTime() over what I'm currently using? –  Lanaru Nov 4 '12 at 19:16
    
From reading stackoverflow.com/questions/351565/… I'd pick System.nanoTime() - it might make things a touch smoother, especially if TIME_STEP is small. –  Adam Nov 4 '12 at 22:41

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.