文中大體的思路:
-
A玩家 移動時,本機自行移動,并發送移動指令給服務端,假設移動是成功的,服務端同步其他客戶端 B玩家,B玩家 中用一個隊列?Queue?來裝服務端來的移動指令,然后客戶端在updata中做插值 (lerp?) 處理,這樣 A玩家 在 B玩家客戶端中移動起來就比較平滑
-
如果 A玩家 移動很頻繁,B玩家 中的 指令隊列?Queue?會堆積的很大,這里可以做個優化,就是當?Queue?的?size?超過某個臨界值 (threshold)時,加快插值(lerp)的速率
-
A玩家 移動時,本機自行移動 并保留一份此次移動的 副本 (copy)到一個?隊列?中,并發送移動指令給服務端,如果服務端判定移動是失敗的(比如穿墻之類的),則服務端下發指令給 A玩家 修復此次移動的位置,然后?隊列?中移除此次移動的副本
-
關于攻擊時的同步,客戶端A 中自行播放攻擊動作并上行給服務的此次攻擊的指令,服務端同步其他 客戶端B 播放攻擊動作,同時同步給所有客戶端(客戶端A和B)扣血指令,為防止客戶端作弊必須有服務端運行計算實際扣血量。
下面是部分關于位置同步的代碼
using UnityEngine;
using System.Collections;
using UnityEngine.Networking;
using System.Collections.Generic;
[NetworkSettings(channel = 0, sendInterval = 0.1f)]
public class SmoothMove : NetworkBehaviour
{[SyncVar(hook = "SyncPostionsValues")]private Vector3 syncPos; [SerializeField]Transform myTransform; private float lerpRate;private float normalLerpRate = 16.0f;private float fasterLerpRate = 27.0f;private Vector3 lastPos;private float threshold = 0.5f;private List<Vector3> syncPosList = new List<Vector3>();[SerializeField]private bool useHistoriicalLerping = false; private float closeEnough = 0.11f;public void Start(){lerpRate = normalLerpRate;}public void Update(){LerpPosition(); }public void FixedUpdate() //1. server 和 client 都執行FixedUpdate{TransmitPosition(); }void LerpPosition(){if (!isLocalPlayer) {if (useHistoriicalLerping) {HistoryLerping();}else{OrdinaryLerping();}}}[Command]void CmdProvidePositionToServer(Vector3 pos){syncPos = pos; }[Client]void TransmitPosition(){if (isLocalPlayer && Vector3.Distance(myTransform.position, lastPos) > threshold) {CmdProvidePositionToServer(myTransform.position);}}[Client]public void SyncPostionsValues(Vector3 lastPos){syncPos = lastPos;syncPosList.Add(syncPos); }void OrdinaryLerping() {myTransform.position = Vector3.Lerp(myTransform.position, syncPos, Time.deltaTime * lerpRate);}void HistoryLerping() {if (syncPosList.Count > 0){myTransform.position = Vector3.Lerp(myTransform.position, syncPosList[0], Time.deltaTime * lerpRate);if (Vector3.Distance(myTransform.position, syncPosList[0]) < closeEnough){syncPosList.RemoveAt(0);}if (syncPosList.Count > 10){lerpRate = fasterLerpRate;}else{lerpRate = normalLerpRate;}Debug.LogFormat("--- syncPosList, count:{0}", syncPosList.Count);}}
}