I implemented my first ever state interpolation in my game demo a few days ago. If client time and the server time has a time difference less than 10ms the player interpolates very smoothly. However if the time difference is bigger, such as 40ms or 90ms the player will suddenly stop and then after a while just flick to the target position like there is no interpolation at all.
My game demo is very simple. It only shows players moving around on the map. My current interpolation function is like this (written in Javascript):
interpolateState(previousState, currentState, renderTime) {
if (renderTime <= currentState.timestamp && renderTime >= previousState.timestamp) {
const total = currentState.timestamp - previousState.timestamp;
const portion = renderTime - previousState.timestamp;
const ratio = portion / total;
// For every player do the following
player.x = lerp(previousState.players[player.id].x, currentState.players[player.id].x, ratio);
player.y = lerp(previousState.players[player.id].y, currentState.players[player.id].y, ratio);
player.rotation = lerp(previousState.players[player.id].rotation, currentState.players[player.id].rotation, ratio);
} else {
sync(currentState);
}
}
sync(state) {
player.x = findPlayerState(state).x;
player.y = findPlayerState(state).y;
}
Here server runs at 60fps and send update every 50ms and the renderTime is the 200ms before the server time which I get from syncing the time with the server at client side.
On the client I put the states I received from the server into a queue which has 3 slots for storage temporary states so that on every network update the new state will be pushed into the queue and an existing state will be popped out for use. The queue will only pop a state when it's full, and to interpolate I need to have two states, that's why I choose 200ms before the present time. This simple and naive approach seems to work but I think there are a lot to improve to make my game demo playable in real world situation. Is there anything I can work on to fix the lags due to server and client time difference?