Jumping while walking is buggy

Hello everyone, I’m testing the character controller with animations for the first time, and I have this very basic code that kinda works, but unreliably, basically the jump sometimes work, sometimes not. I’m guessing it might be because i have two CharacterController.Move(), but that seems a bit weird, especially considering the tutorial i have based the script on by Brackeys (

) has two Move actions as well. What am missing ?

Thanks a lot !!

public class CharacterMovementTest : MonoBehaviour
{
    float gravity = -9.8f;

    public float WalkSpeed = 1.16f;
    public float TurnSpeed = 85f;
    public float JumpHeight = 3f;

    Vector3 velocity = new Vector3();
    Vector3 move = new Vector3();

    private Animator m_Animator;
    private CharacterController m_CharacterController;
  

    void Start()
    {
        m_Animator = GetComponent<Animator>();
       m_CharacterController = GetComponent<CharacterController>();
    }

    // Update is called once per frame
    void Update()
    {
        //KeepGrounded

        if (m_CharacterController.isGrounded && velocity.y < 0f)
        {
            velocity.y = -2f;
        }

        //walk
        float Vertical = Input.GetAxis("Vertical");
        float Horizontal = Input.GetAxis("Horizontal");

        m_CharacterController.Move(transform.forward * Time.deltaTime * WalkSpeed * Vertical);
      

        //rotate

        transform.Rotate(0f, Horizontal * Time.deltaTime * TurnSpeed, 0f);



        //Jump

        if (Input.GetKeyDown(KeyCode.Space) && m_CharacterController.isGrounded)
        {
            velocity.y = Mathf.Sqrt(JumpHeight * -2f * gravity);
        }

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

    }

Break apart the two conditions on line 47: test for jump first (Space), then ask if it is grounded in separate nested if statements.

If it is not grounded, use Debug.Log to output “NOT GROUNDED” and then you can start to figure out why this is happening. If that doesn’t print, then the problem is something else.

Either way, it is always best to test only one condition at a time so you can reason about faulty logic.

That’s actually what I did first, and it seemed like they both worked separately. without the grounded condition I could jump reliably, and when i debugged the Grounded method it just worked perfectly on its own, so I don’t really know…

Okay I figured it out : basically the CharacterController.isGrounded can’t be called multiple times I guess, so what I did was store it in a separate isGrounded bool that can be used multiple times.

Interesting. The documentation says:

“Was the CharacterController touching the ground during the last move?”

If it is sometimes false when you think you are on the ground, most likely you are just barely off the ground such as with uneven ground, and you’re about to be back on in the next frame or so.