PlayerController.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using Mirror;
  4. using UnityEngine;
  5. using UnityEngine.Audio;
  6. public class PlayerController : NetworkBehaviour
  7. {
  8. public Rigidbody2D rigidbody;
  9. public SpriteRenderer sprite;
  10. public bool invertSprite;
  11. public Animator animator;
  12. public LayerMask groundLayerMask;
  13. // public float drownedDepth;
  14. public bool isGrounded = true;
  15. public bool isSwimming = false;
  16. public Transform groundChecker;
  17. public Vector2 gravity;
  18. public float buoyantForce;
  19. public float buoyantSpd;
  20. public float moveSpeed = 1;
  21. public float jumpForce = 10;
  22. public float jumpDuration = 0.2f;
  23. public AudioClip jumpSFX;
  24. float jumpT = 0;
  25. public bool listenToInput = true;
  26. public bool inDoor = false;
  27. public bool insideDoor = false;
  28. bool enteringDoor = false;
  29. public Vector3 neighboursDetectorSize;
  30. void Start()
  31. {
  32. jumpT = jumpDuration;
  33. if (!isServer)
  34. {
  35. rigidbody.simulated = false;
  36. }
  37. }
  38. [SyncVar]
  39. bool _grounded = false;
  40. bool jumpReleased = true;
  41. [HideInInspector]
  42. public bool inWater;
  43. [SyncVar]
  44. public bool InteractionKeyPressed;
  45. [SyncVar]
  46. public bool JumpKeyPressed;
  47. [SyncVar]
  48. public float HorizontalAxis;
  49. public float moveInput = 0;
  50. [Command]
  51. void CmdUpdateInput(float _horizontal, bool jump, bool interact)
  52. {
  53. HorizontalAxis = _horizontal;
  54. JumpKeyPressed = jump;
  55. InteractionKeyPressed = interact;
  56. }
  57. void ListenInput()
  58. {
  59. HorizontalAxis = 0;
  60. if (Input.GetKey(InputManager.data().leftInput)) { HorizontalAxis = -1; } else if (Input.GetKey(InputManager.data().rightInput)) { HorizontalAxis = 1; }
  61. JumpKeyPressed = Input.GetKey(InputManager.data().jumpInput);
  62. InteractionKeyPressed = Input.GetKey(InputManager.data().interactingKey);
  63. }
  64. void FixedUpdate()
  65. {
  66. if (isLocalPlayer)
  67. { // <-- First Listen to inputs no matter in server or not, but if the lcoal player
  68. ListenInput();
  69. }
  70. Movement();//SImulate everywhere
  71. if (isServer)
  72. { //Simulate physics on server
  73. RpcUpdatePosition(transform.position, HorizontalAxis, rigidbody.velocity, NetworkTime.time);
  74. }
  75. else
  76. {
  77. if (isLocalPlayer)
  78. { //I aint the server, but the local player. I move!
  79. CmdUpdateInput(HorizontalAxis, JumpKeyPressed, InteractionKeyPressed);
  80. }
  81. }
  82. }
  83. [ClientRpc]
  84. void RpcUpdatePosition(Vector3 position, float horizontalAxis, Vector3 velocity, double time)
  85. {
  86. double latency = NetworkTime.time - time;
  87. int framesSkipped = Mathf.FloorToInt((float)(latency * 50));
  88. Debug.Log($"Missed {framesSkipped} frames due to network");
  89. if (Vector3.Distance(transform.position, position) > 0.15f)
  90. {
  91. transform.position = position;
  92. rigidbody.velocity = velocity;
  93. }
  94. // if(isLocalPlayer){
  95. // //Client prediction
  96. // if(Vector3.Distance(transform.position, position) > 0.5f){
  97. // transform.position = position;
  98. // rigidbody.velocity= velocity;
  99. // }
  100. // }else{
  101. // //Just update the position
  102. // transform.position = Vector3.Lerp(transform.position, position, 0.1f);
  103. // rigidbody.velocity=velocity;
  104. // }
  105. }
  106. void Movement()
  107. {
  108. isGrounded = getGrounded();
  109. if (_grounded != isGrounded)
  110. {
  111. if (isGrounded)
  112. {
  113. OnLand();
  114. }
  115. else
  116. {
  117. OnFly();
  118. }
  119. _grounded = isGrounded;
  120. }
  121. if (isSwimming)
  122. {
  123. rigidbody.velocity = new Vector2(rigidbody.velocity.x, Mathf.Lerp(rigidbody.velocity.y, buoyantForce, buoyantSpd));
  124. if ((JumpKeyPressed))
  125. {
  126. rigidbody.velocity = new Vector2(rigidbody.velocity.x, jumpForce / 12f);
  127. }
  128. }
  129. else
  130. {
  131. gravity = new Vector2(gravity.x, 0);
  132. }
  133. //Gravity Application
  134. rigidbody.AddForce(gravity);
  135. //Update In-Air value on animation
  136. animator.SetBool("inAir", !isGrounded);
  137. animator.SetBool("isOnWater", inWater);
  138. // if (GameManager.isPaused) { HorizontalAxis = 0; }
  139. //Move according to input
  140. //Exit the door
  141. if (enteringDoor && !InteractionKeyPressed)
  142. {
  143. enteringDoor = false;
  144. }
  145. if (insideDoor && !enteringDoor && InteractionKeyPressed)
  146. {
  147. Debug.Log("Exiting door");
  148. transform.position = SceneData.netSceneData.door.transform.position;
  149. insideDoor = false;
  150. enteringDoor = true;
  151. if (GetComponent<NetPlayer>() != null) { GetComponent<NetPlayer>().CallChangeInsideDoor(insideDoor); }
  152. }
  153. if (listenToInput)
  154. {
  155. if (isGrounded)
  156. {
  157. moveInput = HorizontalAxis;
  158. }
  159. else
  160. {
  161. //Change moveInput while in-air | IF there is an input
  162. // if (Input.GetKey(InputManager.data().leftInput) || Input.GetKey(InputManager.data().rightInput))
  163. if (HorizontalAxis != 0)
  164. {
  165. moveInput = Mathf.Lerp(moveInput, HorizontalAxis, 0.2f);
  166. }
  167. }
  168. //Enter the door
  169. if (inDoor && InteractionKeyPressed && !enteringDoor)
  170. {
  171. if (SceneData.netSceneData.doorExit != null)
  172. {
  173. Debug.Log("Entering door");
  174. transform.DetachChildren();
  175. transform.position = SceneData.netSceneData.doorExit.position;
  176. insideDoor = true;
  177. enteringDoor = true;
  178. if (GetComponent<NetPlayer>() != null) { GetComponent<NetPlayer>().CallChangeInsideDoor(insideDoor); }
  179. }
  180. }
  181. }
  182. if (isSwimming || inWater) { moveInput = moveInput / 2f; }
  183. //Update moving value on Animation
  184. animator.SetBool("moving", (moveInput != 0));
  185. animator.SetBool("isSwimming", isSwimming);
  186. //Flip Image to face moving Direction
  187. if (moveInput < 0)
  188. {
  189. sprite.flipX = (invertSprite) ? false : true;
  190. }
  191. else if (moveInput > 0)
  192. {
  193. sprite.flipX = (invertSprite) ? true : false;
  194. }
  195. //Apply moving input to player
  196. // if (GetComponent<NetPlayer>() != null)
  197. // {
  198. // if (GetComponent<NetPlayer>().parentFrnd != null)
  199. // {
  200. // rigidbody.velocity = GetComponent<NetPlayer>().parentFrnd.GetComponent<Rigidbody2D>().velocity;
  201. // }
  202. // }
  203. rigidbody.transform.Translate(new Vector2(moveSpeed * moveInput, 0));
  204. if (moveInput == 0)
  205. {
  206. rigidbody.constraints = RigidbodyConstraints2D.FreezePositionX | RigidbodyConstraints2D.FreezeRotation;
  207. }
  208. else
  209. {
  210. rigidbody.constraints = RigidbodyConstraints2D.FreezeRotation;
  211. }
  212. bool _canJump = canJump();
  213. if ((JumpKeyPressed) && _canJump)
  214. {
  215. jumpT = 0;
  216. jumpReleased = false;
  217. rigidbody.velocity = new Vector2(rigidbody.velocity.x, 0);
  218. if (jumpSFX != null) AudioSingleton.getSFXSource().PlayOneShot(jumpSFX);
  219. }
  220. //Blocks continous jump button
  221. if (!JumpKeyPressed) { jumpReleased = true; }
  222. //Apply Jump to player
  223. if (jumpT < jumpDuration)
  224. {
  225. jumpT += Time.deltaTime;
  226. float progress = (jumpDuration - jumpT) / jumpDuration;
  227. //|| jumpT < jumpDuration/2f
  228. if ((JumpKeyPressed) || b) { rigidbody.AddForce(new Vector2(0, jumpForce * progress)); }
  229. }
  230. else { b = false; }
  231. _isSwimming = inWater;
  232. }
  233. bool b;
  234. bool _isSwimming;
  235. public bool waterBoost;
  236. public bool canJump()
  237. {
  238. return jumpT >= jumpDuration && isGrounded && listenToInput && jumpReleased && !isSwimming && transform.childCount <= 0;//&& !GameManager.isPaused
  239. }
  240. public bool canBotJump()
  241. {
  242. return isGrounded || isSwimming || inWater;
  243. }
  244. //External Player Control Exposure
  245. public void Jump()
  246. {
  247. jumpT = 0;
  248. rigidbody.velocity = new Vector2(rigidbody.velocity.x, 0);
  249. b = true;
  250. AudioSingleton.getSFXSource().PlayOneShot(jumpSFX);
  251. }
  252. public void move(float input)
  253. {
  254. input = Mathf.Clamp(input, -1, 1);
  255. moveInput = input;
  256. }
  257. void OnLand()
  258. {
  259. // Debug.Log("Landed Like a boss!");
  260. }
  261. void OnFly()
  262. {
  263. // Debug.Log("Hey look im flying");
  264. }
  265. public float groundCheckerDist = 0.1f;
  266. public float groundCheckerHeighMultipler = 1f;
  267. public bool getGrounded()
  268. {
  269. //return (Physics2D.Linecast(transform.position, groundChecker.position, groundLayerMask));
  270. Collider2D col = GetComponentInChildren<Collider2D>();
  271. return (Physics2D.BoxCast(col.bounds.center, new Vector2(col.bounds.size.x - (col.bounds.size.x / 5f), col.bounds.size.y * groundCheckerHeighMultipler), 0, Vector2.down, groundCheckerDist, groundLayerMask));
  272. }
  273. void OnDrawGizmos()
  274. {
  275. Collider2D col = GetComponentInChildren<Collider2D>();
  276. Gizmos.DrawWireCube(transform.position, neighboursDetectorSize);
  277. Gizmos.color = Color.red;
  278. Gizmos.DrawWireCube(col.bounds.center - new Vector3(0, groundCheckerDist), new Vector2(col.bounds.size.x - (col.bounds.size.x / 5f), col.bounds.size.y * groundCheckerHeighMultipler));
  279. }
  280. // public bool getInWater(){Collider2D col = GetComponentInChildren<Collider2D>();
  281. // return (Physics2D.BoxCast(col.bounds.center, new Vector2(col.bounds.size.x - (col.bounds.size.x / 5f), col.bounds.size.y), 0, Vector2.down, 0.1f, waterLayerMask));
  282. // }
  283. }
  284. public static class AudioSingleton
  285. {
  286. private static AudioSource music;
  287. private static AudioSource sfx;
  288. public static AudioMixer mixer = Resources.Load("MasterMixer") as AudioMixer;
  289. public static AudioSource getMusicSource()
  290. {
  291. if (music == null)
  292. {
  293. GameObject go = new GameObject("Music Audio Source");
  294. go.AddComponent<AudioSource>();
  295. music = go.GetComponent<AudioSource>();
  296. music.outputAudioMixerGroup = mixer.FindMatchingGroups("Music")[0];
  297. }
  298. return music;
  299. }
  300. public static AudioSource getSFXSource()
  301. {
  302. //AudioMixer mixer = Resources.Load("MasterMixer") as AudioMixer;
  303. if (sfx == null)
  304. {
  305. GameObject go = new GameObject("SFX Audio Source");
  306. go.AddComponent<AudioSource>();
  307. sfx = go.GetComponent<AudioSource>();
  308. Debug.Log("sfx : " + (sfx == null).ToString() + ", mixer: " + (mixer == null).ToString());
  309. sfx.outputAudioMixerGroup = mixer.FindMatchingGroups("SFX")[0];
  310. }
  311. return sfx;
  312. }
  313. }