| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104 |
- 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<Rigidbody>();
- 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;
- }
- }
|