quantum-space-buddies/QSB/TransformSync/TransformSync.cs

77 lines
2.4 KiB
C#
Raw Normal View History

using UnityEngine;
using UnityEngine.Networking;
2020-02-21 22:36:07 +00:00
namespace QSB.TransformSync
{
public abstract class TransformSync : NetworkBehaviour
{
private const float SmoothTime = 0.1f;
private static bool _isAwake;
private Transform _syncedTransform;
private bool _isSectorSetUp;
private Vector3 _positionSmoothVelocity;
private Quaternion _rotationSmoothVelocity;
protected virtual void Awake()
{
DontDestroyOnLoad(this);
if (_isAwake)
{
OnWakeUp();
}
else
{
GlobalMessenger.AddListener("WakeUp", OnWakeUp);
}
}
protected abstract Transform InitLocalTransform();
protected abstract Transform InitRemoteTransform();
private void OnWakeUp()
{
_isAwake = true;
DebugLog.Screen("Start TransformSync", netId.Value);
Invoke(nameof(SetFirstSector), 1);
transform.parent = Locator.GetRootTransform();
_syncedTransform = hasAuthority ? InitLocalTransform() : InitRemoteTransform();
}
private void SetFirstSector()
{
_isSectorSetUp = true;
2020-02-21 22:36:07 +00:00
SectorSync.Instance.SetSector(netId.Value, Locator.GetAstroObject(AstroObject.Name.TimberHearth).transform);
}
public void EnterSector(Sector sector)
{
2020-02-21 22:36:07 +00:00
SectorSync.Instance.SetSector(netId.Value, sector.GetName());
}
private void Update()
{
if (!_syncedTransform || !_isSectorSetUp)
{
return;
}
2020-02-21 22:36:07 +00:00
var sectorTransform = SectorSync.Instance.GetSector(netId.Value);
if (hasAuthority)
{
transform.position = sectorTransform.InverseTransformPoint(_syncedTransform.position);
transform.rotation = sectorTransform.InverseTransformRotation(_syncedTransform.rotation);
}
else
{
_syncedTransform.parent = sectorTransform;
_syncedTransform.localPosition = Vector3.SmoothDamp(_syncedTransform.localPosition, transform.position, ref _positionSmoothVelocity, SmoothTime);
2020-02-21 22:36:07 +00:00
_syncedTransform.localRotation = QuaternionHelper.SmoothDamp(_syncedTransform.localRotation, transform.rotation, ref _rotationSmoothVelocity, Time.deltaTime);
}
}
}
}