#if COM_UNITY_MODULES_PHYSICS2D using UnityEngine; namespace Unity.Netcode.Components { /// /// NetworkRigidbody allows for the use of on network objects. By controlling the kinematic /// mode of the rigidbody and disabling it on all peers but the authoritative one. /// [RequireComponent(typeof(Rigidbody2D))] [RequireComponent(typeof(NetworkTransform))] [AddComponentMenu("Netcode/Network Rigidbody 2D")] public class NetworkRigidbody2D : NetworkBehaviour { /// /// Determines if we are server (true) or owner (false) authoritative /// private bool m_IsServerAuthoritative; private Rigidbody2D m_Rigidbody; private NetworkTransform m_NetworkTransform; private RigidbodyInterpolation2D m_OriginalInterpolation; // Used to cache the authority state of this rigidbody during the last frame private bool m_IsAuthority; private void Awake() { m_NetworkTransform = GetComponent(); m_IsServerAuthoritative = m_NetworkTransform.IsServerAuthoritative(); SetupRigidBody(); } /// /// If the current has authority, /// then use the interpolation strategy, /// if the is handling interpolation, /// set interpolation to none on the ///
/// Turn off physics for the rigid body until spawned, otherwise /// clients can run fixed update before the first /// full update ///
private void SetupRigidBody() { m_Rigidbody = GetComponent(); m_OriginalInterpolation = m_Rigidbody.interpolation; m_Rigidbody.interpolation = m_IsAuthority ? m_OriginalInterpolation : (m_NetworkTransform.Interpolate ? RigidbodyInterpolation2D.None : m_OriginalInterpolation); // Turn off physics for the rigid body until spawned, otherwise // clients can run fixed update before the first full // NetworkTransform update m_Rigidbody.isKinematic = true; } /// /// For owner authoritative (i.e. ClientNetworkTransform) /// we adjust our authority when we gain ownership /// public override void OnGainedOwnership() { UpdateOwnershipAuthority(); } /// /// For owner authoritative(i.e. ClientNetworkTransform) /// we adjust our authority when we have lost ownership /// public override void OnLostOwnership() { UpdateOwnershipAuthority(); } /// /// Sets the authority differently depending upon /// whether it is server or owner authoritative /// private void UpdateOwnershipAuthority() { if (m_IsServerAuthoritative) { m_IsAuthority = NetworkManager.IsServer; } else { m_IsAuthority = IsOwner; } // If you have authority then you are not kinematic m_Rigidbody.isKinematic = !m_IsAuthority; // Set interpolation of the Rigidbody2D based on authority // With authority: let local transform handle interpolation // Without authority: let the NetworkTransform handle interpolation m_Rigidbody.interpolation = m_IsAuthority ? m_OriginalInterpolation : RigidbodyInterpolation2D.None; } /// public override void OnNetworkSpawn() { UpdateOwnershipAuthority(); } /// public override void OnNetworkDespawn() { UpdateOwnershipAuthority(); } } } #endif // COM_UNITY_MODULES_PHYSICS2D