Advertisement
Guest User

Untitled

a guest
Feb 11th, 2016
47
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 9.31 KB | None | 0 0
  1. using UnityEngine;
  2. using System.Collections;
  3. using UnityStandardAssets.CrossPlatformInput;
  4.  
  5. public class CharacterController2D : MonoBehaviour {
  6. // player controls
  7. [Range(0.0f, 10.0f)] // create a slider in the editor and set limits on moveSpeed
  8. public float moveSpeed = 3f;
  9.  
  10. public float jumpForce = 600f;
  11.  
  12. // player health
  13. public int playerHealth = 1;
  14.  
  15. // LayerMask to determine what is considered ground for the player
  16. public LayerMask whatIsGround;
  17.  
  18. // Transform just below feet for checking if player is grounded
  19. public Transform groundCheck;
  20.  
  21. // player can move?
  22. // we want this public so other scripts can access it but we don't want to show in editor as it might confuse designer
  23. [HideInInspector]
  24. public bool playerCanMove = true;
  25.  
  26. // SFXs
  27. public AudioClip coinSFX;
  28. public AudioClip deathSFX;
  29. public AudioClip fallSFX;
  30. public AudioClip jumpSFX;
  31. public AudioClip victorySFX;
  32.  
  33.  
  34. // private variables below
  35.  
  36. // store references to components on the gameObject
  37. Transform _transform;
  38. Rigidbody2D _rigidbody;
  39. Animator _animator;
  40. AudioSource _audio;
  41. ParticleSystem particleRed;
  42.  
  43. // hold player motion in this timestep
  44. float _vx;
  45. float _vy;
  46.  
  47. // player tracking
  48. bool facingRight = true;
  49. bool isGrounded = false;
  50. bool isRunning = false;
  51. bool _canDoubleJump = false;
  52.  
  53. // store the layer the player is on (setup in Awake)
  54. int _playerLayer;
  55.  
  56. // number of layer that Platforms are on (setup in Awake)
  57. int _platformLayer;
  58.  
  59. void Awake () {
  60. // get a reference to the components we are going to be changing and store a reference for efficiency purposes
  61. _transform = GetComponent<Transform> ();
  62.  
  63. _rigidbody = GetComponent<Rigidbody2D> ();
  64. if (_rigidbody==null) // if Rigidbody is missing
  65. Debug.LogError("Rigidbody2D component missing from this gameobject");
  66.  
  67. _animator = GetComponent<Animator>();
  68. if (_animator==null) // if Animator is missing
  69. Debug.LogError("Animator component missing from this gameobject");
  70.  
  71. _audio = GetComponent<AudioSource> ();
  72. if (_audio==null) { // if AudioSource is missing
  73. Debug.LogWarning("AudioSource component missing from this gameobject. Adding one.");
  74. // let's just add the AudioSource component dynamically
  75. _audio = gameObject.AddComponent<AudioSource>();
  76. }
  77. particleRed = GetComponent<ParticleSystem>();
  78.  
  79. // determine the player's specified layer
  80. _playerLayer = this.gameObject.layer;
  81.  
  82. // determine the platform's specified layer
  83. _platformLayer = LayerMask.NameToLayer("Platform");
  84. }
  85.  
  86. // this is where most of the player controller magic happens each game event loop
  87. void Update()
  88. {
  89. // exit update if player cannot move or game is paused
  90. if (!playerCanMove || (Time.timeScale == 0f))
  91. return;
  92.  
  93. // determine horizontal velocity change based on the horizontal input
  94. _vx = CrossPlatformInputManager.GetAxisRaw ("Horizontal");
  95.  
  96. // Determine if running based on the horizontal movement
  97. if (_vx != 0)
  98. {
  99. isRunning = true;
  100. } else {
  101. isRunning = false;
  102. }
  103.  
  104. // set the running animation state
  105. _animator.SetBool("Running", isRunning);
  106.  
  107. // get the current vertical velocity from the rigidbody component
  108. _vy = _rigidbody.velocity.y;
  109.  
  110. // Check to see if character is grounded by raycasting from the middle of the player
  111. // down to the groundCheck position and see if collected with gameobjects on the
  112. // whatIsGround layer
  113. isGrounded = Physics2D.Linecast(_transform.position, groundCheck.position, whatIsGround);
  114.  
  115. // Allow Double Jump after grounded
  116. if (isGrounded)
  117. {
  118. _canDoubleJump = true;
  119. }
  120. // Set the grounded animation states
  121. _animator.SetBool("Grounded", isGrounded);
  122.  
  123. if (isGrounded && CrossPlatformInputManager.GetButtonDown ("Jump")) { // If grounded AND jump button pressed, then allow the player to jump
  124. DoJump ();
  125. } else if (_canDoubleJump && CrossPlatformInputManager.GetButtonDown ("Jump"))
  126. {
  127. DoJump();
  128. // double jumo can be possible once
  129. _canDoubleJump = false;
  130. }
  131.  
  132. // If the player stops jumping mid jump and player is not yet falling
  133. // then set the vertical velocity to 0 (he will start to fall from gravity)
  134. if(CrossPlatformInputManager.GetButtonUp("Jump") && _vy>0f)
  135. {
  136. _vy = 0f;
  137. }
  138.  
  139. // Change the actual velocity on the rigidbody
  140. _rigidbody.velocity = new Vector2(_vx * moveSpeed, _vy);
  141.  
  142. // if moving up then don't collide with platform layer
  143. // this allows the player to jump up through things on the platform layer
  144. // NOTE: requires the platforms to be on a layer named "Platform"
  145. Physics2D.IgnoreLayerCollision(_playerLayer, _platformLayer, (_vy > 0.0f));
  146.  
  147. }
  148.  
  149. // Checking to see if the sprite should be flipped
  150. // this is done in LateUpdate since the Animator may override the localScale
  151. // this code will flip the player even if the animator is controlling scale
  152. void LateUpdate()
  153. {
  154. // get the current scale
  155. Vector3 localScale = _transform.localScale;
  156.  
  157. if (_vx > 0) // moving right so face right
  158. {
  159. facingRight = true;
  160. } else if (_vx < 0) { // moving left so face left
  161. facingRight = false;
  162. }
  163.  
  164. // check to see if scale x is right for the player
  165. // if not, multiple by -1 which is an easy way to flip a sprite
  166. if (((facingRight) && (localScale.x<0)) || ((!facingRight) && (localScale.x>0))) {
  167. localScale.x *= -1;
  168. }
  169.  
  170. // update the scale
  171. _transform.localScale = localScale;
  172. }
  173.  
  174. // if the player collides with a MovingPlatform, then make it a child of that platform
  175. // so it will go for a ride on the MovingPlatform
  176. void OnCollisionEnter2D(Collision2D other)
  177. {
  178. if (other.gameObject.tag=="MovingPlatform")
  179. {
  180. this.transform.parent = other.transform;
  181. }
  182. }
  183.  
  184. // if the player exits a collision with a moving platform, then unchild it
  185. void OnCollisionExit2D(Collision2D other)
  186. {
  187. if (other.gameObject.tag=="MovingPlatform")
  188. {
  189. this.transform.parent = null;
  190. }
  191. }
  192.  
  193. //make the player jump
  194. void DoJump()
  195. {
  196. // reset current vertical motion to 0 prior to jump
  197. _vy = 0f;
  198. // add a force in the up direction
  199. _rigidbody.AddForce (new Vector2 (0, jumpForce));
  200. // play the jump sound
  201. PlaySound(jumpSFX);
  202. }
  203. // do what needs to be done to freeze the player
  204. void FreezeMotion() {
  205. playerCanMove = false;
  206. _rigidbody.isKinematic = true;
  207. }
  208.  
  209. // do what needs to be done to unfreeze the player
  210. void UnFreezeMotion() {
  211. playerCanMove = true;
  212. _rigidbody.isKinematic = false;
  213. }
  214.  
  215. // play sound through the audiosource on the gameobject
  216. void PlaySound(AudioClip clip)
  217. {
  218. _audio.PlayOneShot(clip);
  219. }
  220.  
  221. // public function to apply damage to the player
  222. public void ApplyDamage (int damage) {
  223. if (playerCanMove) {
  224. playerHealth -= damage;
  225.  
  226. if (playerHealth <= 0) { // player is now dead, so start dying
  227. PlaySound(deathSFX);
  228.  
  229. StartCoroutine (KillPlayer ());
  230.  
  231. }
  232. }
  233. }
  234.  
  235. // public function to kill the player when they have a fall death
  236. public void FallDeath () {
  237. if (playerCanMove) {
  238. playerHealth = 0;
  239. PlaySound(fallSFX);
  240.  
  241. StartCoroutine (KillPlayer ());
  242.  
  243. }
  244.  
  245. }
  246.  
  247. // coroutine to kill the player
  248. IEnumerator KillPlayer()
  249. {
  250. if (playerCanMove)
  251. {
  252. // freeze the player
  253. FreezeMotion();
  254.  
  255. // play the death animation
  256. _animator.SetTrigger("Death");
  257.  
  258. // After waiting tell the GameManager to reset the game
  259. yield return new WaitForSeconds(2.0f);
  260.  
  261. if (GameManager.gm) // if the gameManager is available, tell it to reset the game
  262. GameManager.gm.ResetGame();
  263. else // otherwise, just reload the current level
  264. Application.LoadLevel(Application.loadedLevelName);
  265. }
  266. }
  267.  
  268. public void CollectCoin(int amount) {
  269. PlaySound(coinSFX);
  270.  
  271. if (GameManager.gm) // add the points through the game manager, if it is available
  272. GameManager.gm.AddPoints(amount);
  273. }
  274.  
  275. // public function on victory over the level
  276. public void Victory() {
  277. PlaySound(victorySFX);
  278. FreezeMotion ();
  279. _animator.SetTrigger("Victory");
  280.  
  281. if (GameManager.gm) // do the game manager level compete stuff, if it is available
  282. GameManager.gm.LevelCompete();
  283. }
  284.  
  285. // public function to respawn the player at the appropriate location
  286. public void Respawn(Vector3 spawnloc) {
  287. UnFreezeMotion();
  288. playerHealth = 1;
  289. _transform.parent = null;
  290. _transform.position = spawnloc;
  291. _animator.SetTrigger("Respawn");
  292. }
  293.  
  294. public void EnemyBounce ()
  295. {
  296. DoJump ();
  297. }
  298. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement