PlayerManager.cs 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  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. private bool leavingRoom;
  102. /// <summary>
  103. /// MonoBehaviour method called on GameObject by Unity on every frame.
  104. /// Process Inputs if local player.
  105. /// Show and hide the beams
  106. /// Watch for end of game, when local player health is 0.
  107. /// </summary>
  108. public void Update()
  109. {
  110. // we only process Inputs and check health if we are the local player
  111. if (photonView.IsMine)
  112. {
  113. this.ProcessInputs();
  114. if (this.Health <= 0f && !this.leavingRoom)
  115. {
  116. this.leavingRoom = PhotonNetwork.LeaveRoom();
  117. }
  118. }
  119. if (this.beams != null && this.IsFiring != this.beams.activeInHierarchy)
  120. {
  121. this.beams.SetActive(this.IsFiring);
  122. }
  123. }
  124. public override void OnLeftRoom()
  125. {
  126. this.leavingRoom = false;
  127. }
  128. /// <summary>
  129. /// MonoBehaviour method called when the Collider 'other' enters the trigger.
  130. /// Affect Health of the Player if the collider is a beam
  131. /// Note: when jumping and firing at the same, you'll find that the player's own beam intersects with itself
  132. /// One could move the collider further away to prevent this or check if the beam belongs to the player.
  133. /// </summary>
  134. public void OnTriggerEnter(Collider other)
  135. {
  136. if (!photonView.IsMine)
  137. {
  138. return;
  139. }
  140. // We are only interested in Beamers
  141. // we should be using tags but for the sake of distribution, let's simply check by name.
  142. if (!other.name.Contains("Beam"))
  143. {
  144. return;
  145. }
  146. this.Health -= 0.1f;
  147. }
  148. /// <summary>
  149. /// MonoBehaviour method called once per frame for every Collider 'other' that is touching the trigger.
  150. /// We're going to affect health while the beams are interesting the player
  151. /// </summary>
  152. /// <param name="other">Other.</param>
  153. public void OnTriggerStay(Collider other)
  154. {
  155. // we dont' do anything if we are not the local player.
  156. if (!photonView.IsMine)
  157. {
  158. return;
  159. }
  160. // We are only interested in Beamers
  161. // we should be using tags but for the sake of distribution, let's simply check by name.
  162. if (!other.name.Contains("Beam"))
  163. {
  164. return;
  165. }
  166. // we slowly affect health when beam is constantly hitting us, so player has to move to prevent death.
  167. this.Health -= 0.1f*Time.deltaTime;
  168. }
  169. #if !UNITY_5_4_OR_NEWER
  170. /// <summary>See CalledOnLevelWasLoaded. Outdated in Unity 5.4.</summary>
  171. void OnLevelWasLoaded(int level)
  172. {
  173. this.CalledOnLevelWasLoaded(level);
  174. }
  175. #endif
  176. /// <summary>
  177. /// MonoBehaviour method called after a new level of index 'level' was loaded.
  178. /// We recreate the Player UI because it was destroy when we switched level.
  179. /// Also reposition the player if outside the current arena.
  180. /// </summary>
  181. /// <param name="level">Level index loaded</param>
  182. void CalledOnLevelWasLoaded(int level)
  183. {
  184. // check if we are outside the Arena and if it's the case, spawn around the center of the arena in a safe zone
  185. if (!Physics.Raycast(transform.position, -Vector3.up, 5f))
  186. {
  187. transform.position = new Vector3(0f, 5f, 0f);
  188. }
  189. GameObject _uiGo = Instantiate(this.playerUiPrefab);
  190. _uiGo.SendMessage("SetTarget", this, SendMessageOptions.RequireReceiver);
  191. }
  192. #endregion
  193. #region Private Methods
  194. #if UNITY_5_4_OR_NEWER
  195. void OnSceneLoaded(UnityEngine.SceneManagement.Scene scene, UnityEngine.SceneManagement.LoadSceneMode loadingMode)
  196. {
  197. this.CalledOnLevelWasLoaded(scene.buildIndex);
  198. }
  199. #endif
  200. /// <summary>
  201. /// Processes the inputs. This MUST ONLY BE USED when the player has authority over this Networked GameObject (photonView.isMine == true)
  202. /// </summary>
  203. void ProcessInputs()
  204. {
  205. if (Input.GetButtonDown("Fire1"))
  206. {
  207. // we don't want to fire when we interact with UI buttons for example. IsPointerOverGameObject really means IsPointerOver*UI*GameObject
  208. // 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.
  209. if (EventSystem.current.IsPointerOverGameObject())
  210. {
  211. // return;
  212. }
  213. if (!this.IsFiring)
  214. {
  215. this.IsFiring = true;
  216. }
  217. }
  218. if (Input.GetButtonUp("Fire1"))
  219. {
  220. if (this.IsFiring)
  221. {
  222. this.IsFiring = false;
  223. }
  224. }
  225. }
  226. #endregion
  227. #region IPunObservable implementation
  228. public void OnPhotonSerializeView(PhotonStream stream, PhotonMessageInfo info)
  229. {
  230. if (stream.IsWriting)
  231. {
  232. // We own this player: send the others our data
  233. stream.SendNext(this.IsFiring);
  234. stream.SendNext(this.Health);
  235. }
  236. else
  237. {
  238. // Network player, receive data
  239. this.IsFiring = (bool)stream.ReceiveNext();
  240. this.Health = (float)stream.ReceiveNext();
  241. }
  242. }
  243. #endregion
  244. }
  245. }