Hello. I have the following script for my character movement. the problem is, when the character is in mid-air and the jump key (space) is pressed, it jumps automatically after it lands on the ground. my code is:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Movement : MonoBehaviour
{
[SerializeField] float moveSpeed = 6;
[SerializeField] float jumpHeight = 2;
[SerializeField] float gravity = 20;
[Range(0, 10), SerializeField] float airControl = 5;
Vector3 moveDirection = Vector3.zero;
CharacterController controller;
bool IsJumpPressed;
void Start()
{
controller = GetComponent<CharacterController>();
}
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
IsJumpPressed = true;
}
}
void FixedUpdate()
{
var input = new Vector3(
Input.GetAxis("Horizontal"),
0,
Input.GetAxis("Vertical")
);
input *= moveSpeed;
input = transform.TransformDirection(input);
if (controller.isGrounded)
{
moveDirection = input;
if (IsJumpPressed)
{
moveDirection.y = Mathf.Sqrt(2 * gravity * jumpHeight);
IsJumpPressed = false;
}
else
{
moveDirection.y = 0;
}
}
else
{
input.y = moveDirection.y;
moveDirection = Vector3.Lerp(moveDirection, input,
airControl * Time.deltaTime);
}
moveDirection.y -= gravity * Time.deltaTime;
controller.Move(moveDirection * Time.deltaTime);
}
}