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

75 lines
2.0 KiB
C#
Raw Normal View History

2021-08-14 14:03:01 +00:00
using QSB.Syncs.Sectored.Rigidbodies;
2021-12-14 00:02:31 +00:00
using QSB.Utility;
2021-11-19 08:28:36 +00:00
using UnityEngine;
2022-03-03 03:46:33 +00:00
namespace QSB.ShipSync.TransformSync;
public class ShipTransformSync : SectoredRigidbodySync
{
2022-03-03 03:46:33 +00:00
public static ShipTransformSync LocalInstance { get; private set; }
2022-03-03 03:46:33 +00:00
private float _lastSetPositionTime;
private const float ForcePositionAfterTime = 1;
2022-01-15 05:34:09 +00:00
2022-03-03 03:46:33 +00:00
protected override bool CheckReady() =>
base.CheckReady() &&
Locator.GetShipBody();
2022-03-03 03:46:33 +00:00
public override void OnStartClient()
{
base.OnStartClient();
LocalInstance = this;
}
protected override OWRigidbody InitAttachedRigidbody()
{
SectorDetector.Init(Locator.GetShipDetector().GetComponent<SectorDetector>());
return Locator.GetShipBody();
}
2022-01-15 05:34:09 +00:00
2022-03-03 03:46:33 +00:00
/// Dont do base... this is a replacement!
protected override void ApplyToAttached()
{
ApplyToSector();
if (!ReferenceTransform)
{
2022-03-03 03:46:33 +00:00
return;
}
2022-01-15 05:34:09 +00:00
2022-03-03 03:46:33 +00:00
var targetPos = ReferenceTransform.FromRelPos(transform.position);
2022-01-15 05:34:09 +00:00
2022-03-03 03:46:33 +00:00
if (Time.unscaledTime >= _lastSetPositionTime + ForcePositionAfterTime)
{
_lastSetPositionTime = Time.unscaledTime;
2022-01-15 05:34:09 +00:00
2022-03-03 03:46:33 +00:00
var targetRot = ReferenceTransform.FromRelRot(transform.rotation);
2022-01-15 05:34:09 +00:00
2022-03-03 03:46:33 +00:00
AttachedRigidbody.SetPosition(targetPos);
AttachedRigidbody.SetRotation(targetRot);
}
2022-01-15 05:34:09 +00:00
2022-03-03 03:46:33 +00:00
var targetVelocity = ReferenceRigidbody.FromRelVel(Velocity, targetPos);
var targetAngularVelocity = ReferenceRigidbody.FromRelAngVel(AngularVelocity);
2022-01-15 05:34:09 +00:00
2022-03-03 03:46:33 +00:00
SetVelocity(AttachedRigidbody, targetVelocity);
AttachedRigidbody.SetAngularVelocity(targetAngularVelocity);
}
2022-03-03 03:46:33 +00:00
/// use OWRigidbody version instead of ShipBody override
private static void SetVelocity(OWRigidbody rigidbody, Vector3 newVelocity)
{
if (rigidbody.RunningKinematicSimulation())
{
rigidbody._kinematicRigidbody.velocity = newVelocity + Locator.GetCenterOfTheUniverse().GetStaticFrameVelocity_Internal();
2022-01-15 05:34:09 +00:00
}
2022-03-03 03:46:33 +00:00
else
2022-01-15 05:34:09 +00:00
{
2022-03-03 03:46:33 +00:00
rigidbody._rigidbody.velocity = newVelocity + Locator.GetCenterOfTheUniverse().GetStaticFrameVelocity_Internal();
2022-01-15 05:34:09 +00:00
}
2022-03-03 03:46:33 +00:00
rigidbody._lastVelocity = rigidbody._currentVelocity;
rigidbody._currentVelocity = newVelocity;
2022-01-15 05:34:09 +00:00
}
2022-03-03 03:46:33 +00:00
protected override bool UseInterpolation => false;
}