Hi all,
I’m using the standard Unity networking, but I’m having issues with syncing the player movement. I understand I have to use Vector3.Lerp() and some other odd things that I do not understand, but after following a guide I cannot get it to work. My PlayerPrefab is using a CharacterController, so accessing a RigidBody wouldn’t obviously work.
I took code from a tutorial that uses a rigidbody, and then transformed it to use the PlayerPrefab’s transform and the CharacterController’s velocity.
private float lastSynchronizationTime = 0f;
private float syncDelay = 0f;
private float syncTime = 0f;
private Vector3 syncPosition = Vector3.zero;
private Vector3 syncVelocity = Vector3.zero;
private Quaternion syncRotation = Quaternion.identity;
private Vector3 syncStartPosition = Vector3.zero;
private Vector3 syncEndPosition = Vector3.zero;
// Update is called once per frame
void Update () {
if (networkView.isMine)
{
UpdateMovement();
}
else
{
SyncedMovement();
}
}
void OnSerializeNetworkView(BitStream stream, NetworkMessageInfo info)
{
if (stream.isWriting)
{
syncPosition = transform.position;
stream.Serialize(ref syncPosition);
syncVelocity = GetComponent<CharacterController>().velocity;
stream.Serialize(ref syncVelocity);
syncRotation = transform.rotation;
stream.Serialize(ref syncRotation);
}
else
{
stream.Serialize(ref syncPosition);
stream.Serialize(ref syncVelocity);
stream.Serialize(ref syncRotation);
transform.position = syncPosition;
transform.rotation = syncRotation;
syncTime = 0f;
syncDelay = Time.time - lastSynchronizationTime;
lastSynchronizationTime = Time.time;
syncEndPosition = (syncPosition + syncVelocity) * syncDelay;
syncStartPosition = transform.position;
}
}
void SyncedMovement()
{
syncTime += Time.deltaTime;
transform.position = Vector3.Lerp(syncStartPosition, syncEndPosition, syncTime / syncDelay);
}
Yes, some of the code is missing. I have only provided the Network Syncing section of the player controller.