|
using System; |
|
using System.Threading; |
|
using Cysharp.Threading.Tasks; |
|
using Photon.Pun; |
|
using UnityEngine; |
|
|
|
namespace Nekomimi.Daimao.Photon |
|
{ |
|
public class PhotonTransformShare : MonoBehaviour, IPunObservable |
|
{ |
|
private void Start() |
|
{ |
|
ShareLoop(this.GetCancellationTokenOnDestroy()).Forget(); |
|
} |
|
|
|
public bool IsWrite = false; |
|
|
|
public Vector3 SharePos; |
|
public Quaternion ShareRot; |
|
|
|
public int IntervalMsec = 100; |
|
|
|
public float LerpTime = 0.1f; |
|
|
|
public int LastReceivedTimeDiff = 0; |
|
public int CurrentDiff = 0; |
|
|
|
public float WarpDistance = 1f; |
|
public int WarpTime = 1000; |
|
|
|
private async UniTaskVoid ShareLoop(CancellationToken token) |
|
{ |
|
var ts = this.transform; |
|
|
|
while (true) |
|
{ |
|
if (token.IsCancellationRequested) |
|
{ |
|
break; |
|
} |
|
if (IsWrite) |
|
{ |
|
await UniTask.Delay(TimeSpan.FromMilliseconds(IntervalMsec), cancellationToken: token); |
|
SharePos = ts.localPosition; |
|
ShareRot = ts.localRotation; |
|
} |
|
else |
|
{ |
|
await UniTask.Yield(token); |
|
|
|
if (LastReceivedTimeDiff > WarpTime |
|
|| Vector3.SqrMagnitude(SharePos - ts.localPosition) > Mathf.Pow(WarpDistance, 2f)) |
|
{ |
|
ts.localPosition = SharePos; |
|
ts.localRotation = ShareRot; |
|
continue; |
|
} |
|
|
|
var time = Time.deltaTime / LerpTime; |
|
ts.localPosition = Vector3.LerpUnclamped(ts.localPosition, SharePos, time); |
|
ts.localRotation = Quaternion.LerpUnclamped(ts.localRotation, ShareRot, time); |
|
} |
|
} |
|
} |
|
|
|
public void OnPhotonSerializeView(PhotonStream stream, PhotonMessageInfo info) |
|
{ |
|
IsWrite = stream.IsWriting; |
|
LastReceivedTimeDiff = info.SentServerTimestamp - LastReceivedTimeDiff; |
|
CurrentDiff = PhotonNetwork.ServerTimestamp - info.SentServerTimestamp; |
|
|
|
if (IsWrite) |
|
{ |
|
stream.SendNext(SharePos); |
|
stream.SendNext(ShareRot); |
|
} |
|
else |
|
{ |
|
SharePos = (Vector3) stream.ReceiveNext(); |
|
ShareRot = (Quaternion) stream.ReceiveNext(); |
|
} |
|
} |
|
} |
|
} |