quantum-space-buddies/QSB/Syncs/QSBNetworkTransformChild.cs

66 lines
1.8 KiB
C#
Raw Normal View History

using Mirror;
using QSB.Utility;
using UnityEngine;
2022-03-02 19:46:33 -08:00
namespace QSB.Syncs;
2022-08-27 11:44:52 -07:00
[UsedInUnityProject]
2022-03-02 19:46:33 -08:00
public class QSBNetworkTransformChild : QSBNetworkBehaviour
{
2022-03-02 19:46:33 -08:00
public Transform Target;
2022-03-02 19:46:33 -08:00
protected override float SendInterval => 0.05f;
2022-03-02 19:46:33 -08:00
private const float PositionChangeThreshold = 0.05f;
private const float RotationChangeThreshold = 0.05f;
2022-03-02 19:46:33 -08:00
private Vector3 _prevPosition;
private Quaternion _prevRotation;
2022-03-02 19:46:33 -08:00
protected override bool HasChanged() =>
Vector3.Distance(Target.localPosition, _prevPosition) > PositionChangeThreshold ||
Quaternion.Angle(Target.localRotation, _prevRotation) > RotationChangeThreshold;
2022-03-02 19:46:33 -08:00
protected override void Serialize(NetworkWriter writer)
{
writer.Write(Target.localPosition);
writer.Write(Target.localRotation);
}
2022-03-02 19:46:33 -08:00
protected override void UpdatePrevData()
{
_prevPosition = Target.localPosition;
_prevRotation = Target.localRotation;
}
2022-02-25 11:50:00 -08:00
2022-03-02 19:46:33 -08:00
protected override void Deserialize(NetworkReader reader)
{
Target.localPosition = reader.ReadVector3();
Target.localRotation = reader.ReadQuaternion();
}
2022-02-27 06:28:59 -08:00
2022-03-02 19:46:33 -08:00
public Transform AttachedTransform { get; internal set; }
2022-02-27 06:28:59 -08:00
2022-03-02 19:46:33 -08:00
private const float SmoothTime = 0.1f;
private Vector3 _positionSmoothVelocity;
private Quaternion _rotationSmoothVelocity;
2022-02-27 06:28:59 -08:00
2022-03-02 19:46:33 -08:00
protected override void Update()
{
if (AttachedTransform)
2022-02-27 06:28:59 -08:00
{
2022-03-02 19:46:33 -08:00
if (hasAuthority)
2022-02-27 06:28:59 -08:00
{
2022-03-02 19:46:33 -08:00
Target.localPosition = AttachedTransform.localPosition;
Target.localRotation = AttachedTransform.localRotation;
}
else
{
AttachedTransform.localPosition = Vector3.SmoothDamp(AttachedTransform.localPosition, Target.localPosition, ref _positionSmoothVelocity, SmoothTime);
AttachedTransform.localRotation = QuaternionHelper.SmoothDamp(AttachedTransform.localRotation, Target.localRotation, ref _rotationSmoothVelocity, SmoothTime);
2022-02-27 06:28:59 -08:00
}
}
2022-03-02 19:46:33 -08:00
base.Update();
}
2022-03-02 19:46:33 -08:00
}