using UnityEngine;

public class PlayerMovement : MonoBehaviour {
    public CharacterController controller;
    public float gravity = -9.81f;
    public Transform groundCheck;
    public float groundDistance = 0.4f;
    public LayerMask groundMask;
    private bool isOnGround;
    public float jumpHeight = 2f;
    public float MovementSpeed = 10f;

    private Vector3 velocity;

    private void Update() {
        isOnGround = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);

        if (isOnGround && velocity.y < 0) velocity.y = -2f;

        var x = Input.GetAxis("Horizontal");
        var z = Input.GetAxis("Vertical");
        var move = transform.right * x + transform.forward * z;

        controller.Move(move * MovementSpeed * Time.deltaTime);
        if (Input.GetButtonDown("Jump") && isOnGround) velocity.y = Mathf.Sqrt(jumpHeight * -2 * gravity);

        velocity.y += gravity * Time.deltaTime;
        controller.Move(velocity * Time.deltaTime);
    }
}