学习Unity,正在尝试使用自带的Network组件做局域网的相关测试。
发现对象在使用NavMeshAgent时,用NetworkTransform组件同步位置(只能使用SyncTransfomr模式)非常不理想,没有做一个平滑移动效果。
在搜索了一番相关文章后,问题得以解决(目测可行),总结了如下代码:
SyncLerpMove .cs
using UnityEngine;
using UnityEngine.Networking;[RequireComponent(typeof(NetworkIdentity))]
public class SyncLerpMove : NetworkBehaviour{/// <summary>/// 一秒内同步的次数/// </summary>public int NetworkSendRate = 9;private float nextSyncTime;/*同步3D坐标*/public bool SyncTransform3D = true;[SyncVar]private Vector3 syncPosition3D;/*同步转向*/public bool SyncRotation3D = true;[SyncVar]private Quaternion syncRotation3D;void Awake () {//删除NetworkTransform组件(如果存在)//NetworkTransform network = GetComponent<NetworkTransform>();//if (network) Destroy(network);}void FixedUpdate () {nextSyncTime -= Time.fixedDeltaTime;if (isServer || isLocalPlayer){if (nextSyncTime > 0) return;nextSyncTime = 1f / NetworkSendRate;if (isServer) SendServerPos();else CmdSendServerPos(transform.position, transform.rotation);}else{LerpPosition();}}/// <summary>/// 插值平滑移动/// </summary>public void LerpPosition(){if(SyncTransform3D && Vector3.Distance(transform.position,syncPosition3D)>0.1f)transform.position = Vector3.Lerp(transform.position, syncPosition3D, 5 * Time.fixedDeltaTime);if(SyncRotation3D && Quaternion.Angle(transform.rotation, syncRotation3D)>0.1f)transform.rotation = Quaternion.Lerp(transform.rotation, syncRotation3D, 5 * Time.fixedDeltaTime);}/// <summary>/// 客户端更新至服务器端,服务器发送给所有客户端/// </summary>[Command]public void CmdSendServerPos(Vector3 pos, Quaternion rotate){if (SyncTransform3D) syncPosition3D = pos;if (SyncRotation3D) syncRotation3D = rotate;}/// <summary>/// 服务器端,发送给所有客户端/// </summary>public void SendServerPos(){if (SyncTransform3D) syncPosition3D = transform.position;if (SyncRotation3D) syncRotation3D = transform.rotation;}
}