using UnityEngine; public class PlayerMovement : MonoBehaviour { [Header("Movement")] public float moveSpeed; public float groundDrag; public float jumpForce; public float jumpCooldown; public float airMultiplier; bool readyToJump; [Header("Keybinds")] public KeyCode jumpKey = KeyCode.Space; [Header("Ground Check")] public float playerHeight; public LayerMask whatIsGround; bool grounded; public Transform orientation; float horizontalInput; float verticalInput; Vector3 moveDirection; Rigidbody rb; private void Start() { rb = GetComponent(); rb.freezeRotation = true; readyToJump = true; } private void Update() { // ground check grounded = Physics.Raycast(transform.position, Vector3.down, playerHeight * 0.5f + 0.3f, whatIsGround); MyInput(); // handle drag if (grounded) rb.linearDamping = groundDrag; else rb.linearDamping = 0; } private void FixedUpdate() { MovePlayer(); } private void MyInput() { horizontalInput = Input.GetAxisRaw("Horizontal"); verticalInput = Input.GetAxisRaw("Vertical"); // when to jump if(Input.GetKey(jumpKey) && readyToJump && grounded) { readyToJump = false; Jump(); Invoke(nameof(ResetJump), jumpCooldown); } } private void MovePlayer() { // calculate movement direction moveDirection = orientation.forward * verticalInput + orientation.right * horizontalInput; // on ground if(grounded) rb.AddForce(moveDirection.normalized * moveSpeed * 10f, ForceMode.Force); // in air else if(!grounded) rb.AddForce(moveDirection.normalized * moveSpeed * 10f * airMultiplier, ForceMode.Force); } private void Jump() { // reset y velocity rb.linearVelocity = new Vector3(rb.linearVelocity.x, 0f, rb.linearVelocity.z); rb.AddForce(transform.up * jumpForce, ForceMode.Impulse); } private void ResetJump() { readyToJump = true; } }