Unity3d 插值同步
生活随笔
收集整理的這篇文章主要介紹了
Unity3d 插值同步
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
文中大體的思路:
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;/// <summary> /// 可以通過 /// 1. 減少發包率(意思就是 增大 sendInterval 發包間隔) /// 2. 增大 closeEnough 距離 /// 3. 增大 normalLerpRate、fasterLerpRate 插值速率 /// </summary>[NetworkSettings(channel = 0, sendInterval = 0.1f)] public class SmoothMove : NetworkBehaviour {[SyncVar(hook = "SyncPostionsValues")]private Vector3 syncPos; //同步變量[SerializeField]Transform myTransform; //SerializeField用于inspector中顯示非public變量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; //是否啟用平滑插值的開關,直接在 inspector 中設置private float closeEnough = 0.11f;public void Start(){lerpRate = normalLerpRate;}public void Update(){LerpPosition(); //因為方法利用了Time.deltaTime,所以只能在 Updata中調用}public void FixedUpdate() //1. server 和 client 都執行FixedUpdate{TransmitPosition(); //2. 因為是 ClientCallback,所以只有客戶端調用}void LerpPosition(){if (!isLocalPlayer) //5. 只有非本機玩家才進行插值移動到最新的 syncPos 位置{if (useHistoriicalLerping) //更加平滑{HistoryLerping();}else{OrdinaryLerping();}}}[Command]void CmdProvidePositionToServer(Vector3 pos){syncPos = pos; //4. 服務端收到信息同步給所有客戶端的該對象的syncPos變量}[Client]void TransmitPosition(){if (isLocalPlayer && Vector3.Distance(myTransform.position, lastPos) > threshold) //3. 只用本機玩家才提交位置信息到server上{CmdProvidePositionToServer(myTransform.position);}}[Client]public void SyncPostionsValues(Vector3 lastPos){syncPos = lastPos;syncPosList.Add(syncPos); //將所有服務端同步過來的 pos 全都保存在隊列中}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);}} }總結
以上是生活随笔為你收集整理的Unity3d 插值同步的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 主成分分析(PCA)原理详解 2016
- 下一篇: void Update ( ) 更新