NetworkLerpRigidbody.cs 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. using System;
  2. using UnityEngine;
  3. namespace Mirror.Experimental
  4. {
  5. [AddComponentMenu("Network/ Experimental/Network Lerp Rigidbody")]
  6. [HelpURL("https://mirror-networking.gitbook.io/docs/components/network-lerp-rigidbody")]
  7. [Obsolete("Use the new NetworkRigidbodyReliable/Unreliable component with Snapshot Interpolation instead.")]
  8. public class NetworkLerpRigidbody : NetworkBehaviour
  9. {
  10. [Header("Settings")]
  11. [SerializeField] internal Rigidbody target = null;
  12. [Tooltip("How quickly current velocity approaches target velocity")]
  13. [SerializeField] float lerpVelocityAmount = 0.5f;
  14. [Tooltip("How quickly current position approaches target position")]
  15. [SerializeField] float lerpPositionAmount = 0.5f;
  16. [Tooltip("Set to true if moves come from owner client, set to false if moves always come from server")]
  17. [SerializeField] bool clientAuthority = false;
  18. double nextSyncTime;
  19. [SyncVar()]
  20. Vector3 targetVelocity;
  21. [SyncVar()]
  22. Vector3 targetPosition;
  23. /// <summary>
  24. /// Ignore value if is host or client with Authority
  25. /// </summary>
  26. bool IgnoreSync => isServer || ClientWithAuthority;
  27. bool ClientWithAuthority => clientAuthority && isOwned;
  28. protected override void OnValidate()
  29. {
  30. base.OnValidate();
  31. if (target == null)
  32. target = GetComponent<Rigidbody>();
  33. }
  34. void Update()
  35. {
  36. if (isServer)
  37. SyncToClients();
  38. else if (ClientWithAuthority)
  39. SendToServer();
  40. }
  41. void SyncToClients()
  42. {
  43. targetVelocity = target.velocity;
  44. targetPosition = target.position;
  45. }
  46. void SendToServer()
  47. {
  48. double now = NetworkTime.localTime; // Unity 2019 doesn't have Time.timeAsDouble yet
  49. if (now > nextSyncTime)
  50. {
  51. nextSyncTime = now + syncInterval;
  52. CmdSendState(target.velocity, target.position);
  53. }
  54. }
  55. [Command]
  56. void CmdSendState(Vector3 velocity, Vector3 position)
  57. {
  58. target.velocity = velocity;
  59. target.position = position;
  60. targetVelocity = velocity;
  61. targetPosition = position;
  62. }
  63. void FixedUpdate()
  64. {
  65. if (IgnoreSync) { return; }
  66. target.velocity = Vector3.Lerp(target.velocity, targetVelocity, lerpVelocityAmount);
  67. target.position = Vector3.Lerp(target.position, targetPosition, lerpPositionAmount);
  68. // add velocity to position as position would have moved on server at that velocity
  69. target.position += target.velocity * Time.fixedDeltaTime;
  70. // TODO does this also need to sync acceleration so and update velocity?
  71. }
  72. }
  73. }