NetworkLerpRigidbody.cs 2.7 KB

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