Character jumps immediately after it's grounded when jump is pressed mid-air
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);
}
}
Answer by Hellium · Aug 17, 2021 at 09:46 PM
if (Input.GetKeyDown(KeyCode.Space) && controller.isGrounded)
{
IsJumpPressed = true;
}
OR
set IsJumpPressed
to false at the end of the FixedUpdate
Thanks, This fixed the issue (I tried: && controller.isGrounded) Have a nice day.
Answer by bigcartert101 · Aug 17, 2021 at 09:08 PM
if (Input.GetKeyDown(KeyCode.Space))
{
IsJumpPressed = true;
}
This makes it so that IsJumpPressed stays true until a jump happens, and a jump happens if you are on the ground and IsJumpPressed=true. That is why you are jumping immediately. try
if (controller.isGrounded)
{
moveDirection = input;
if (Input.GetKeyDown(KeyCode.Space))
{
moveDirection.y = Mathf.Sqrt(2 * gravity * jumpHeight);
}
else
{
moveDirection.y = 0;
}
}
and not have the IsJumpPressed.
That Fixes the issue, but creates another problem. The reason i used 'IsJumpPressed' in the 'Update Method' was because if you use it in 'FixedUpdate' it will only detect it when you press the key at the start of a frame (i guess, sort of thing) and that makes it pretty hard to jump, you have to press space several times until one hits right.
what if you did a late update to set IsJumpPressed to false?