Interpolating between player positions

If we were to only run our game in a LAN environment, we would probably never expect low latency or any significant packet loss. While many are blessed even with good Internet connections nowadays, from time to time, problems still happen. One of the tricks to try to mitigate these problems is to use interpolation for entities on the client side.

This means that rather than just applying the position and rotation the client gets from the server, the client will move towards the target position and rotation in steps.

How to do it...

Perform the following steps to interpolate between the player positions:

  1. To simulate some network problems, set framerate on the server to 10.
  2. If you connect to the server now, the movement will be noticeably jerky.
  3. We replace the contents of the controlUpdate method of ClientPlayerControl with the following lines to apply the interpolation:
    float factor = tpf / 0.03f; spatial.setLocalTranslation(spatial.getLocalTranslation().interpolateLocal(tempLocation, factor)); spatial.setLocalRotation(spatial.getLocalRotation().slerp(spatial.getLocalRotation(), tempRotation, factor));
  4. When we connect again and compare the experience, it will be much smoother.

How it works...

To simulate an environment with problems such as packet loss, we changed the FPS on the server to 10. Instead of sending out the 30 updates per second it did before, it will only send one every tenth of a second. This is not the same as 100 ms of latency, since it says nothing about the turnaround time. It's more as if two out of three updates were lost on the way, a 66 percent packet loss.

Previously, the client simply took the values it got from the server and applied them to the local players. Using interpolation, the player's position and rotation will move towards the latest actual position and rotation in steps every update.

We implemented the interpolation by first determining the interpolation factor. This was done by dividing tpf by the amount of time (roughly, in seconds) we would like the interpolation to take. The actual time will be longer since the steps become shorter with each update.

We then input this value and use the interpolation method of Vector3f and the slerp method of Quaternion to move them towards the actual values.

This is done by using a factor based on the tpf value provided in the update method. By doing so, the interpolation time will be roughly the same regardless of the frame rate. We should be aware that this in reality becomes latency, a delay between the action and appearance, as we have added a slight delay to when the player reaches the actual position.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.138.123.106