I am tweaking my client code to interpolate movements between the server position and the client's current position. This seems to work "ok" but I still notice a little bit a jitter when the NPC is being interpolated to his destination. Hopefully someone could inspect this code and see what I am doing wrong. I ported this from another post I found. http://www.gamedev.net/topic/639568-network-interpolation-help/.
To test this I am setting up an NPC on the server side to move 0.3f every ~16 msec, BUT I send the position packet at ~160 msec. Perhaps this test case is wrong or inaccurate? Note : the "Update" method is manually called from an entity manager class every frame.
using UnityEngine;
using System.Collections;
using SharedNetworkLibrary.Types;
public class EntityType
{
public int ID { get; private set; }
private GameObject _gameObject;
private Vector3 _displayPosition;
private Vector3 _latestPosition;
private float _latestPositionTime;
private string _currentAnimation = "idle";
private Vector3 _previousPosition;
private bool _isMoving = false;
private const float _interpolationPeriod = 0.3f;
private Animation _animation;
public EntityType(int id, GameObject gameObject)
{
ID = id;
_gameObject = gameObject;
_animation = _gameObject.GetComponentInChildren<Animation> ();
}
// Update is called once per frame
public void Update ()
{
if (_isMoving == true)
{
float t = 1.0f - ((_latestPositionTime - Time.time) / _interpolationPeriod);
_displayPosition = Vector3.Lerp (_previousPosition, _latestPosition, t);
}
else
{
_displayPosition = _latestPosition;
}
_gameObject.transform.position = _displayPosition;
}
public void UpdateAnimation(string animation)
{
_currentAnimation = animation;
}
public void UpdatePosition(EntityStateType entityType)
{
if (entityType.IsMoving == true)
{
_isMoving = true;
_latestPosition = new Vector3 (entityType.X, entityType.Y, entityType.Z);
_latestPositionTime = Time.time + _interpolationPeriod;
_previousPosition = _displayPosition;
if(_animation.isPlaying == false)
{
if(_currentAnimation.Length > 0)
{
_animation.Play (_currentAnimation);
}
}
}
else
{
_isMoving = false;
}
}
}