Search code examples
c#unity-game-enginenetwork-programmingunity3d-unetunity3d-mirror

Syncronize player position in unity (Mirror)


Goal: Syncronize player position in a multiplayer game in Unity that uses the Mirror Networking API

Problem:

  1. Using the NetworkTransform component the position seems to not be precisely syncronized, both the client and the server sees the player in the wrong position, players tend to fly with no reason

  2. I tried making a separated script:


using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Mirror;

public class PlayerSyncronization : NetworkBehaviour
{
    [SyncVar]
    public Vector3 syncPosition;
    [SyncVar]
    public Quaternion syncRotation;

    public float lerpRate = 15;

    private void FixedUpdate()
    {
        TransmitPosition();
        Lerp();
    }
    void Lerp()
    {
        if (!hasAuthority) return;
        transform.position = Vector3.Lerp(transform.position, syncPosition, Time.deltaTime * lerpRate);
        transform.rotation = Quaternion.Lerp(transform.rotation, syncRotation, Time.deltaTime * lerpRate);
    }

    [ClientCallback]
    void TransmitPosition()
    {
        CmdProvidePositionToServer(transform.position, transform.rotation);
    }

    [Command]
    void CmdProvidePositionToServer(Vector3 pos, Quaternion rot)
    {
        syncPosition = pos;
        syncRotation = rot;
    }
}

but the result is the same of the network transform component, and even if a player stops walking, on the other side he keeps walking till he falls off the map

Those are the errors/warning i got using the script

Info:

  • Player movement is client side as I'm using root motion.
  • I can't use IsLocalPlayer as it works only if the player is directly spawned by the NetworkManger and my players are being spawned by a separated script.
  • Right now, even if I'm not using it, i have a CharacterController in my PlayerPrefab
  • I'm using Steamworks to make the players connect through internet

If more info are needed just tell me.


Solution

  • I understood that the problem was the Character controller I was using, so in the player script I checked if the player had authority, if not I destroyed the character controller, and if i was destroying it on the server I replaced it with a normal collider without physics, so i could still have collisions