0
\$\begingroup\$

My server looks like this -

    var timestep = 1000/30;
    var delta = 0;
    var lastFrameTimeMs = 0;

    function panic() {
        delta = 0;
    }


    var update = function(){
        currentTime = Date.now()

        if (currentTime < lastFrameTimeMs + (timestep)) {
            setTimeout(update);
            return;
        }


        delta += currentTime - lastFrameTimeMs;
        lastFrameTimeMs = currentTime;

        let numUpdateSteps = 0;

        previousTime = currentTime;

        while (delta >= timestep) {
            player.update(timestep/1000)

        }
        delta -= timestep;

        if (++numUpdateSteps >= 240) {

            panic(); // fix things
            break; // bail out
        }
        setTimeout(update, 60)
    }
    setTimeout(update, 60)

and then my client looks like -

var timestep = 1000/30;
var delta = 0;
var lastFrameTimeMs = 0;

function panic() {
    delta = 0; // discard the unsimulated time
    // ... snap the player to the authoritative state
}

function mainLoop(timestamp) {
    // Throttle the frame rate.
    if (timestamp < lastFrameTimeMs + (timestep)) {
        requestAnimationFrame(mainLoop);
        return;
    }
    delta += timestamp - lastFrameTimeMs;
    lastFrameTimeMs = timestamp;

    let numUpdateSteps = 0;

    while (delta >= timestep) {
        if(player != undefined) {
            player.update(timestep/1000);
        }
        delta -= timestep;

        if (++numUpdateSteps >= 240) {
            panic(); // fix things
            break; // bail out
        }
    }

    requestAnimationFrame(mainLoop);
}
requestAnimationFrame(mainLoop);

I've been trying to get this work for days. I'm trying to have a fixed time step on both the client and server so they both simulate physics exactly the same down to the decimal point. But for some reason my client is moving much faster than my server. I used this article as a reference.

https://www.isaacsukin.com/news/2015/01/detailed-explanation-javascript-game-loops-and-timing

Where am I doing something wrong in one of my loops? They both use a .033333333333 timestep like I want them to, but they move at different speeds. What am I doing wrong?

\$\endgroup\$
1
  • 3
    \$\begingroup\$ How do you guarantee that both sides will call player.update() the same number of times? \$\endgroup\$ – amitp Nov 29 '16 at 22:43
1
\$\begingroup\$

In addition to @Nat's answer, you should find a way of calculating when the server got the info from client and using that info to predict the new position. Or even better using extrapolation.

There's a whole wikipedia page about this.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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