PlayerController.cs 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. public class PlayerController : MonoBehaviour
  5. {
  6. public Animator playerAnimator;
  7. public Rigidbody playerRigidbody;
  8. public float walkSpeed, walkBackwardSpeed, oldWalkSpeed, runSpeed, rotateSpeed;
  9. public float jumpHeight = 500f;
  10. public bool isWalking;
  11. public bool hasJumped = false;
  12. public bool isGrounded = true;
  13. public Transform playerTransform;
  14. private void FixedUpdate()
  15. {
  16. if (Input.GetKey(KeyCode.W))
  17. {
  18. playerRigidbody.linearVelocity = transform.forward * walkSpeed * Time.deltaTime;
  19. }
  20. if (Input.GetKey(KeyCode.S))
  21. {
  22. playerRigidbody.linearVelocity = -transform.forward * walkBackwardSpeed * Time.deltaTime;
  23. }
  24. }
  25. private void Update()
  26. {
  27. if(Input.GetKeyDown(KeyCode.W))
  28. {
  29. playerAnimator.SetBool("IsWalking", true);
  30. isWalking = true;
  31. }
  32. if (Input.GetKeyUp(KeyCode.W))
  33. {
  34. playerAnimator.SetBool("IsWalking", false);
  35. isWalking = false;
  36. }
  37. if (Input.GetKeyDown(KeyCode.S))
  38. {
  39. playerAnimator.SetBool("IsWalkingBackward", true);
  40. }
  41. if (Input.GetKeyUp(KeyCode.S))
  42. {
  43. playerAnimator.SetBool("IsWalkingBackward", false);
  44. }
  45. if (Input.GetKey(KeyCode.A))
  46. {
  47. playerTransform.Rotate(0, -rotateSpeed * Time.deltaTime, 0);
  48. }
  49. if(Input.GetKey(KeyCode.D))
  50. {
  51. playerTransform.Rotate(0, rotateSpeed * Time.deltaTime, 0);
  52. }
  53. if (Input.GetKeyDown(KeyCode.Space) && isGrounded)
  54. {
  55. playerRigidbody.AddForce(Vector3.up * jumpHeight, ForceMode.Impulse);
  56. playerAnimator.SetTrigger("Jump");
  57. isGrounded = false;
  58. playerAnimator.SetBool("IsGrounded", false);
  59. }
  60. if (isWalking == true)
  61. {
  62. if (Input.GetKeyDown(KeyCode.LeftShift))
  63. {
  64. walkSpeed = walkSpeed + runSpeed;
  65. playerAnimator.SetBool("IsRunning", true);
  66. }
  67. if (Input.GetKeyUp(KeyCode.LeftShift))
  68. {
  69. walkSpeed = oldWalkSpeed;
  70. playerAnimator.SetBool("IsRunning", false);
  71. }
  72. }
  73. }
  74. private void OnCollisionStay(Collision collision)
  75. {
  76. foreach(ContactPoint contact in collision.contacts)
  77. {
  78. if (contact.normal.y > 0.9f)
  79. {
  80. isGrounded = true;
  81. playerAnimator.SetBool("IsGrounded", true);
  82. return;
  83. }
  84. }
  85. }
  86. private void OnCollisionExit(Collision collision)
  87. {
  88. isGrounded = false;
  89. playerAnimator.SetBool("IsGrounded", false);
  90. }
  91. }