I'm developing a First-Person game using the new input system. The issue I'm facing is jumping. when I press Space to jump, I can jump again while the player is still in the air, I can jump multiple times till the player fly. This should not happen. the player should jump only when he is grounded.
public class MyPlayerMovement : MonoBehaviour
{
private InputMaster controls;
private float moveSpeed = 8f;
private float runSpeed = 50f;
private Vector3 velocity;
private float gravity = -9.8f;
private Vector2 move;
private float run;
private float jumpHeight = 2.4f;
private CharacterController controller;
public Transform ground;
public float distanceToGround = 0.4f;
[SerializeField] LayerMask groundMask;
private bool isGrounded;
private bool isRunning;
private void Awake()
{
controls = new InputMaster();
controller = GetComponent<CharacterController>();
controls.Player.Run.started += _ => isRunning = true;
controls.Player.Run.canceled += _ => isRunning = false;
}
void Update()
{
Grav();
PlayerMovement();
Jump();
// check if Run button is pressed
if (isRunning)
{
run = controls.Player.Run.ReadValue<float>();
Vector3 running = (move.y * transform.forward) + (move.x * transform.right);
controller.Move(running * runSpeed * Time.deltaTime);
}
}
private void PlayerMovement()
{
move = controls.Player.Movement.ReadValue<Vector2>();
Vector3 movement = (move.y * transform.forward) + (move.x * transform.right);
controller.Move(movement * moveSpeed * Time.deltaTime);
}
private void Jump()
{
if (controls.Player.Jump.triggered)
{
velocity.y = Mathf.Sqrt(jumpHeight * -2f * gravity);
}
}
public void OnRun()
{
isRunning = !isRunning;
}
private void Grav()
{
//handeling gravity
isGrounded = Physics.CheckSphere(transform.position, distanceToGround, groundMask);
if (isGrounded && velocity.y < 0)
{
velocity.y = -2f;
}
velocity.y += gravity * Time.deltaTime;
controller.Move(velocity * Time.deltaTime);
}
private void OnEnable()
{
controls.Enable();
}
private void OnDisable()
{
controls.Disable();
}
}
I tried to fix this issue by changing the jump condition to this :
if (controls.Player.Jump.triggered && isGrounded)
but now the player does not jump at all. How can I make this work?