SmoothSyncMovement.cs 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. // --------------------------------------------------------------------------------------------------------------------
  2. // <copyright file="SmoothSyncMovement.cs" company="Exit Games GmbH">
  3. // Part of: Photon Unity Utilities,
  4. // </copyright>
  5. // <summary>
  6. // Smoothed out movement for network gameobjects
  7. // </summary>
  8. // <author>developer@exitgames.com</author>
  9. // --------------------------------------------------------------------------------------------------------------------
  10. using UnityEngine;
  11. using Photon.Pun;
  12. using Photon.Realtime;
  13. namespace Photon.Pun.UtilityScripts
  14. {
  15. /// <summary>
  16. /// Smoothed out movement for network gameobjects
  17. /// </summary>
  18. [RequireComponent(typeof(PhotonView))]
  19. public class SmoothSyncMovement : Photon.Pun.MonoBehaviourPun, IPunObservable
  20. {
  21. public float SmoothingDelay = 5;
  22. public void Awake()
  23. {
  24. bool observed = false;
  25. foreach (Component observedComponent in this.photonView.ObservedComponents)
  26. {
  27. if (observedComponent == this)
  28. {
  29. observed = true;
  30. break;
  31. }
  32. }
  33. if (!observed)
  34. {
  35. Debug.LogWarning(this + " is not observed by this object's photonView! OnPhotonSerializeView() in this class won't be used.");
  36. }
  37. }
  38. public void OnPhotonSerializeView(PhotonStream stream, PhotonMessageInfo info)
  39. {
  40. if (stream.IsWriting)
  41. {
  42. //We own this player: send the others our data
  43. stream.SendNext(transform.position);
  44. stream.SendNext(transform.rotation);
  45. }
  46. else
  47. {
  48. //Network player, receive data
  49. correctPlayerPos = (Vector3)stream.ReceiveNext();
  50. correctPlayerRot = (Quaternion)stream.ReceiveNext();
  51. }
  52. }
  53. private Vector3 correctPlayerPos = Vector3.zero; //We lerp towards this
  54. private Quaternion correctPlayerRot = Quaternion.identity; //We lerp towards this
  55. public void Update()
  56. {
  57. if (!photonView.IsMine)
  58. {
  59. //Update remote player (smooth this, this looks good, at the cost of some accuracy)
  60. transform.position = Vector3.Lerp(transform.position, correctPlayerPos, Time.deltaTime * this.SmoothingDelay);
  61. transform.rotation = Quaternion.Lerp(transform.rotation, correctPlayerRot, Time.deltaTime * this.SmoothingDelay);
  62. }
  63. }
  64. }
  65. }