PlayerMovement.cs 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. using UnityEngine;
  2. public class PlayerMovement : MonoBehaviour
  3. {
  4. [Header("Movement")]
  5. public float moveSpeed;
  6. public float groundDrag;
  7. public float jumpForce;
  8. public float jumpCooldown;
  9. public float airMultiplier;
  10. bool readyToJump;
  11. [Header("Keybinds")]
  12. public KeyCode jumpKey = KeyCode.Space;
  13. [Header("Ground Check")]
  14. public float playerHeight;
  15. public LayerMask whatIsGround;
  16. bool grounded;
  17. public Transform orientation;
  18. float horizontalInput;
  19. float verticalInput;
  20. Vector3 moveDirection;
  21. Rigidbody rb;
  22. private void Start()
  23. {
  24. rb = GetComponent<Rigidbody>();
  25. rb.freezeRotation = true;
  26. readyToJump = true;
  27. }
  28. private void Update()
  29. {
  30. // ground check
  31. grounded = Physics.Raycast(transform.position, Vector3.down, playerHeight * 0.5f + 0.3f, whatIsGround);
  32. MyInput();
  33. // handle drag
  34. if (grounded)
  35. rb.linearDamping = groundDrag;
  36. else
  37. rb.linearDamping = 0;
  38. }
  39. private void FixedUpdate()
  40. {
  41. MovePlayer();
  42. }
  43. private void MyInput()
  44. {
  45. horizontalInput = Input.GetAxisRaw("Horizontal");
  46. verticalInput = Input.GetAxisRaw("Vertical");
  47. // when to jump
  48. if(Input.GetKey(jumpKey) && readyToJump && grounded)
  49. {
  50. readyToJump = false;
  51. Jump();
  52. Invoke(nameof(ResetJump), jumpCooldown);
  53. }
  54. }
  55. private void MovePlayer()
  56. {
  57. // calculate movement direction
  58. moveDirection = orientation.forward * verticalInput + orientation.right * horizontalInput;
  59. // on ground
  60. if(grounded)
  61. rb.AddForce(moveDirection.normalized * moveSpeed * 10f, ForceMode.Force);
  62. // in air
  63. else if(!grounded)
  64. rb.AddForce(moveDirection.normalized * moveSpeed * 10f * airMultiplier, ForceMode.Force);
  65. }
  66. private void Jump()
  67. {
  68. // reset y velocity
  69. rb.linearVelocity = new Vector3(rb.linearVelocity.x, 0f, rb.linearVelocity.z);
  70. rb.AddForce(transform.up * jumpForce, ForceMode.Impulse);
  71. }
  72. private void ResetJump()
  73. {
  74. readyToJump = true;
  75. }
  76. }