1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117
| 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() { 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); } } }
|