From 39fbaabd3b9b8da11b5ecbf4c848d9ccb260185d Mon Sep 17 00:00:00 2001 From: mischa Date: Thu, 14 Mar 2024 14:59:50 +0800 Subject: [PATCH] perf: PredictedRigidbody FixedUpdate caches sqr computations --- .../Components/PredictedRigidbody/PredictedRigidbody.cs | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/Assets/Mirror/Components/PredictedRigidbody/PredictedRigidbody.cs b/Assets/Mirror/Components/PredictedRigidbody/PredictedRigidbody.cs index 6fee7c59e..30eaea2c1 100644 --- a/Assets/Mirror/Components/PredictedRigidbody/PredictedRigidbody.cs +++ b/Assets/Mirror/Components/PredictedRigidbody/PredictedRigidbody.cs @@ -62,6 +62,7 @@ public class PredictedRigidbody : NetworkBehaviour [Header("Reconciliation")] [Tooltip("Correction threshold in meters. For example, 0.1 means that if the client is off by more than 10cm, it gets corrected.")] public double positionCorrectionThreshold = 0.10; + double positionCorrectionThresholdSqr; // ² cached in Awake [Tooltip("Correction threshold in degrees. For example, 5 means that if the client is off by more than 5 degrees, it gets corrected.")] public double rotationCorrectionThreshold = 5; @@ -133,6 +134,7 @@ void Awake() // cache ² computations motionSmoothingVelocityThresholdSqr = motionSmoothingVelocityThreshold * motionSmoothingVelocityThreshold; motionSmoothingAngularVelocityThresholdSqr = motionSmoothingAngularVelocityThreshold * motionSmoothingAngularVelocityThreshold; + positionCorrectionThresholdSqr = positionCorrectionThreshold * positionCorrectionThreshold; } protected virtual void CopyRenderersAsGhost(GameObject destination, Material material) @@ -449,7 +451,11 @@ void FixedUpdate() { // TODO maybe don't reuse the correction thresholds? tf.GetPositionAndRotation(out Vector3 position, out Quaternion rotation); - if (Vector3.Distance(lastRecorded.position, position) < positionCorrectionThreshold && + // clean & simple: + // if (Vector3.Distance(lastRecorded.position, position) < positionCorrectionThreshold && + // Quaternion.Angle(lastRecorded.rotation, rotation) < rotationCorrectionThreshold) + // faster: + if ((lastRecorded.position - position).sqrMagnitude < positionCorrectionThresholdSqr && Quaternion.Angle(lastRecorded.rotation, rotation) < rotationCorrectionThreshold) { // Debug.Log($"FixedUpdate for {name}: taking optimized early return instead of recording state.");