PlayerManager.cs 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  1. // --------------------------------------------------------------------------------------------------------------------
  2. // <copyright file="PlayerManager.cs" company="Exit Games GmbH">
  3. // Part of: Photon Unity Networking Demos
  4. // </copyright>
  5. // <summary>
  6. // Used in PUN Basics Tutorial to deal with the networked player instance
  7. // </summary>
  8. // <author>developer@exitgames.com</author>
  9. // --------------------------------------------------------------------------------------------------------------------
  10. using UnityEngine;
  11. using UnityEngine.EventSystems;
  12. namespace Photon.Pun.Demo.PunBasics
  13. {
  14. #pragma warning disable 649
  15. /// <summary>
  16. /// Player manager.
  17. /// Handles fire Input and Beams.
  18. /// </summary>
  19. public class PlayerManager : MonoBehaviourPunCallbacks, IPunObservable
  20. {
  21. #region Public Fields
  22. [Tooltip("The current Health of our player")]
  23. public float Health = 1f;
  24. [Tooltip("The local player instance. Use this to know if the local player is represented in the Scene")]
  25. public static GameObject LocalPlayerInstance;
  26. #endregion
  27. #region Private Fields
  28. [Tooltip("The Player's UI GameObject Prefab")]
  29. [SerializeField]
  30. private GameObject playerUiPrefab;
  31. [Tooltip("The Beams GameObject to control")]
  32. [SerializeField]
  33. private GameObject beams;
  34. //True, when the user is firing
  35. bool IsFiring;
  36. #endregion
  37. #region MonoBehaviour CallBacks
  38. /// <summary>
  39. /// MonoBehaviour method called on GameObject by Unity during early initialization phase.
  40. /// </summary>
  41. public void Awake()
  42. {
  43. if (this.beams == null)
  44. {
  45. Debug.LogError("<Color=Red><b>Missing</b></Color> Beams Reference.", this);
  46. }
  47. else
  48. {
  49. this.beams.SetActive(false);
  50. }
  51. // #Important
  52. // used in GameManager.cs: we keep track of the localPlayer instance to prevent instanciation when levels are synchronized
  53. if (photonView.IsMine)
  54. {
  55. LocalPlayerInstance = gameObject;
  56. }
  57. // #Critical
  58. // we flag as don't destroy on load so that instance survives level synchronization, thus giving a seamless experience when levels load.
  59. DontDestroyOnLoad(gameObject);
  60. }
  61. /// <summary>
  62. /// MonoBehaviour method called on GameObject by Unity during initialization phase.
  63. /// </summary>
  64. public void Start()
  65. {
  66. CameraWork _cameraWork = gameObject.GetComponent<CameraWork>();
  67. if (_cameraWork != null)
  68. {
  69. if (photonView.IsMine)
  70. {
  71. _cameraWork.OnStartFollowing();
  72. }
  73. }
  74. else
  75. {
  76. Debug.LogError("<Color=Red><b>Missing</b></Color> CameraWork Component on player Prefab.", this);
  77. }
  78. // Create the UI
  79. if (this.playerUiPrefab != null)
  80. {
  81. GameObject _uiGo = Instantiate(this.playerUiPrefab);
  82. _uiGo.SendMessage("SetTarget", this, SendMessageOptions.RequireReceiver);
  83. }
  84. else
  85. {
  86. Debug.LogWarning("<Color=Red><b>Missing</b></Color> PlayerUiPrefab reference on player Prefab.", this);
  87. }
  88. #if UNITY_5_4_OR_NEWER
  89. // Unity 5.4 has a new scene management. register a method to call CalledOnLevelWasLoaded.
  90. UnityEngine.SceneManagement.SceneManager.sceneLoaded += OnSceneLoaded;
  91. #endif
  92. }
  93. public override void OnDisable()
  94. {
  95. // Always call the base to remove callbacks
  96. base.OnDisable ();
  97. #if UNITY_5_4_OR_NEWER
  98. UnityEngine.SceneManagement.SceneManager.sceneLoaded -= OnSceneLoaded;
  99. #endif
  100. }
  101. /// <summary>
  102. /// MonoBehaviour method called on GameObject by Unity on every frame.
  103. /// Process Inputs if local player.
  104. /// Show and hide the beams
  105. /// Watch for end of game, when local player health is 0.
  106. /// </summary>
  107. public void Update()
  108. {
  109. // we only process Inputs and check health if we are the local player
  110. if (photonView.IsMine)
  111. {
  112. this.ProcessInputs();
  113. if (this.Health <= 0f)
  114. {
  115. GameManager.Instance.LeaveRoom();
  116. }
  117. }
  118. if (this.beams != null && this.IsFiring != this.beams.activeInHierarchy)
  119. {
  120. this.beams.SetActive(this.IsFiring);
  121. }
  122. }
  123. /// <summary>
  124. /// MonoBehaviour method called when the Collider 'other' enters the trigger.
  125. /// Affect Health of the Player if the collider is a beam
  126. /// Note: when jumping and firing at the same, you'll find that the player's own beam intersects with itself
  127. /// One could move the collider further away to prevent this or check if the beam belongs to the player.
  128. /// </summary>
  129. public void OnTriggerEnter(Collider other)
  130. {
  131. if (!photonView.IsMine)
  132. {
  133. return;
  134. }
  135. // We are only interested in Beamers
  136. // we should be using tags but for the sake of distribution, let's simply check by name.
  137. if (!other.name.Contains("Beam"))
  138. {
  139. return;
  140. }
  141. this.Health -= 0.1f;
  142. }
  143. /// <summary>
  144. /// MonoBehaviour method called once per frame for every Collider 'other' that is touching the trigger.
  145. /// We're going to affect health while the beams are interesting the player
  146. /// </summary>
  147. /// <param name="other">Other.</param>
  148. public void OnTriggerStay(Collider other)
  149. {
  150. // we dont' do anything if we are not the local player.
  151. if (!photonView.IsMine)
  152. {
  153. return;
  154. }
  155. // We are only interested in Beamers
  156. // we should be using tags but for the sake of distribution, let's simply check by name.
  157. if (!other.name.Contains("Beam"))
  158. {
  159. return;
  160. }
  161. // we slowly affect health when beam is constantly hitting us, so player has to move to prevent death.
  162. this.Health -= 0.1f*Time.deltaTime;
  163. }
  164. #if !UNITY_5_4_OR_NEWER
  165. /// <summary>See CalledOnLevelWasLoaded. Outdated in Unity 5.4.</summary>
  166. void OnLevelWasLoaded(int level)
  167. {
  168. this.CalledOnLevelWasLoaded(level);
  169. }
  170. #endif
  171. /// <summary>
  172. /// MonoBehaviour method called after a new level of index 'level' was loaded.
  173. /// We recreate the Player UI because it was destroy when we switched level.
  174. /// Also reposition the player if outside the current arena.
  175. /// </summary>
  176. /// <param name="level">Level index loaded</param>
  177. void CalledOnLevelWasLoaded(int level)
  178. {
  179. // check if we are outside the Arena and if it's the case, spawn around the center of the arena in a safe zone
  180. if (!Physics.Raycast(transform.position, -Vector3.up, 5f))
  181. {
  182. transform.position = new Vector3(0f, 5f, 0f);
  183. }
  184. GameObject _uiGo = Instantiate(this.playerUiPrefab);
  185. _uiGo.SendMessage("SetTarget", this, SendMessageOptions.RequireReceiver);
  186. }
  187. #endregion
  188. #region Private Methods
  189. #if UNITY_5_4_OR_NEWER
  190. void OnSceneLoaded(UnityEngine.SceneManagement.Scene scene, UnityEngine.SceneManagement.LoadSceneMode loadingMode)
  191. {
  192. this.CalledOnLevelWasLoaded(scene.buildIndex);
  193. }
  194. #endif
  195. /// <summary>
  196. /// Processes the inputs. This MUST ONLY BE USED when the player has authority over this Networked GameObject (photonView.isMine == true)
  197. /// </summary>
  198. void ProcessInputs()
  199. {
  200. if (Input.GetButtonDown("Fire1"))
  201. {
  202. // we don't want to fire when we interact with UI buttons for example. IsPointerOverGameObject really means IsPointerOver*UI*GameObject
  203. // notice we don't use on on GetbuttonUp() few lines down, because one can mouse down, move over a UI element and release, which would lead to not lower the isFiring Flag.
  204. if (EventSystem.current.IsPointerOverGameObject())
  205. {
  206. // return;
  207. }
  208. if (!this.IsFiring)
  209. {
  210. this.IsFiring = true;
  211. }
  212. }
  213. if (Input.GetButtonUp("Fire1"))
  214. {
  215. if (this.IsFiring)
  216. {
  217. this.IsFiring = false;
  218. }
  219. }
  220. }
  221. #endregion
  222. #region IPunObservable implementation
  223. public void OnPhotonSerializeView(PhotonStream stream, PhotonMessageInfo info)
  224. {
  225. if (stream.IsWriting)
  226. {
  227. // We own this player: send the others our data
  228. stream.SendNext(this.IsFiring);
  229. stream.SendNext(this.Health);
  230. }
  231. else
  232. {
  233. // Network player, receive data
  234. this.IsFiring = (bool)stream.ReceiveNext();
  235. this.Health = (float)stream.ReceiveNext();
  236. }
  237. }
  238. #endregion
  239. }
  240. }