PlayerMovement.cs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. using UnityEngine;
  2. using System.Collections;
  3. public class PlayerMovement : MonoBehaviour
  4. {
  5. public float turnSmoothing = 15f; // A smoothing value for turning the player.
  6. public float speedDampTime = 0.1f; // The damping for the speed parameter
  7. private Animator anim; // Reference to the animator component.
  8. private HashIDs hash; // Reference to the HashIDs.
  9. void Awake ()
  10. {
  11. // Setting up the references.
  12. anim = GetComponent<Animator>();
  13. hash = GameObject.FindGameObjectWithTag(Tags.gameController).GetComponent<HashIDs>();
  14. }
  15. void FixedUpdate ()
  16. {
  17. // Cache the inputs.
  18. float h = Input.GetAxis("Horizontal");
  19. float v = Input.GetAxis("Vertical");
  20. //MovementManagement(h, v, sneak);
  21. MovementManagement(h, v);
  22. }
  23. void Update ()
  24. {
  25. AudioManagement();
  26. }
  27. void MovementManagement (float horizontal, float vertical)
  28. {
  29. // If there is some axis input...
  30. if(horizontal != 0f || vertical != 0f)
  31. {
  32. // ... set the players rotation and set the speed parameter to 5.5f.
  33. Rotating(-horizontal, -vertical);
  34. anim.SetFloat(hash.speedFloat, 5.5f, speedDampTime, Time.deltaTime);
  35. }
  36. else
  37. // Otherwise set the speed parameter to 0.
  38. anim.SetFloat(hash.speedFloat, 0);
  39. }
  40. void Rotating (float horizontal, float vertical)
  41. {
  42. // Create a new vector of the horizontal and vertical inputs.
  43. Vector3 targetDirection = new Vector3(horizontal, 0f, vertical);
  44. // Create a rotation based on this new vector assuming that up is the global y axis.
  45. Quaternion targetRotation = Quaternion.LookRotation(targetDirection, Vector3.up);
  46. // Create a rotation that is an increment closer to the target rotation from the player's rotation.
  47. Quaternion newRotation = Quaternion.Lerp(GetComponent<Rigidbody>().rotation, targetRotation, turnSmoothing * Time.deltaTime);
  48. // Change the players rotation to this new rotation.
  49. GetComponent<Rigidbody>().MoveRotation(newRotation);
  50. }
  51. void AudioManagement ()
  52. {
  53. // If the player is currently in the run state...
  54. if(anim.GetCurrentAnimatorStateInfo(0).fullPathHash == hash.locomotionState)
  55. //if(anim.GetCurrentAnimatorStateInfo(0).nameHash == hash.locomotionState)
  56. {
  57. // ... and if the footsteps are not playing...
  58. if(!GetComponent<AudioSource>().isPlaying)
  59. // ... play them.
  60. GetComponent<AudioSource>().Play();
  61. }
  62. else
  63. // Otherwise stop the footsteps.
  64. GetComponent<AudioSource>().Stop();
  65. }
  66. }