DerangedSenators / copsandrobbers

2D Multiplayer Cops and Robbers Game made with Unity for the Aston University Team project module
https://www.copsandrobbers.co.uk
Apache License 2.0
6 stars 5 forks source link

Make Timer network behaviour. #134

Open nisathnasar opened 3 years ago

nisathnasar commented 3 years ago

As timer is client based, any differences in latencies causes differences in starting time and in ending time. Meaning some get to play when others haven't even begun or already finished the game.

hsravat-4590 commented 3 years ago

Differences in latency would mean that the times are always not going to be synchronised

hsravat-4590 commented 3 years ago

This might improve time sync performance but I assume there will still be issues if latency is bad:

using UnityEngine;
using System.Collections;
using UnityEngine.Networking;

public class NetworkPlayer : NetworkBehaviour
{
    public bool isNetworkTimeSynced = false;

    // timestamp received from server
    private int networkTimestamp;

    // server to client delay
    private int networkTimestampDelayMS;

    // when did we receive timestamp from server
    private float timeReceived;

    protected virtual void Start()
    {
        if (isLocalPlayer)
        {
            CmdRequestTime();
        }
    }

    [Command]
    private void CmdRequestTime()
    {
        int timestamp = NetworkTransport.GetNetworkTimestamp();
        RpcNetworkTimestamp(timestamp);
    }

    [ClientRpc]
    private void RpcNetworkTimestamp(int timestamp)
    {
        isNetworkTimeSynced = true;
        networkTimestamp = timestamp;
        timeReceived = Time.time;

        // if client is a host, assume that there is 0 delay
        if (isServer)
        {
            networkTimestampDelayMS = 0;
        }
        else
        {
            byte error;
            networkTimestampDelayMS = NetworkTransport.GetRemoteDelayTimeMS(
                NetworkManager.singleton.client.connection.hostId,
                NetworkManager.singleton.client.connection.connectionId,
                timestamp,
                out error);
        }
    }

    public float GetServerTime()
    {
        return networkTimestamp + (networkTimestampDelayMS / 1000f) + (Time.time - timeReceived);
    }
}

The above is Unet code so it will need refactoring to Mirror