Skip to content

Instantly share code, notes, and snippets.

@nekomimi-daimao
Last active July 27, 2021 17:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nekomimi-daimao/a04fc1a1bbd6a6b03ce53d3216a4e2e2 to your computer and use it in GitHub Desktop.
Save nekomimi-daimao/a04fc1a1bbd6a6b03ce53d3216a4e2e2 to your computer and use it in GitHub Desktop.
位置共有自作試作
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();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment