2
\$\begingroup\$

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?

\$\endgroup\$
1
  • 1
    \$\begingroup\$ 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. \$\endgroup\$ Nov 4, 2012 at 19:02

1 Answer 1

3
\$\begingroup\$

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();
    }
\$\endgroup\$
2
  • \$\begingroup\$ Absolutely right! Thanks, I'll reread the article. Also, would you recommend Sytem.nanoTime() over what I'm currently using? \$\endgroup\$
    – Lanaru
    Nov 4, 2012 at 19:16
  • \$\begingroup\$ From reading stackoverflow.com/questions/351565/… I'd pick System.nanoTime() - it might make things a touch smoother, especially if TIME_STEP is small. \$\endgroup\$
    – Adam
    Nov 4, 2012 at 22:41

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .