How to properly make CharacterController jump?

I’m trying to add the ability to jump to my CharacterController script, but it doesn’t seem to work right.

Here’s my code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ThirdPersonController : MonoBehaviour
{
    public CharacterController controller;
    public Transform camera;

    public float characterSpeed = 6f;

    public float jumpSpeed = 2.0f;
    public float gravity = 10.0f;

    public float turnSmoothTime = 0.1f;
    float turnSmoothVelocity;

    Vector3 moveDir = Vector3.zero;
    bool jumping = false;
    void Update()
    {
        float horizontal = Input.GetAxisRaw("Horizontal");
        float vertical = Input.GetAxisRaw("Vertical");
        Vector3 direction = new Vector3(horizontal, 0f, vertical).normalized;

        if (direction.sqrMagnitude >= 0.1f)
        {
            float targetAngle = Mathf.Atan2(direction.x, direction.z) * Mathf.Rad2Deg + camera.eulerAngles.y;
            float angle = Mathf.SmoothDampAngle(transform.eulerAngles.y, targetAngle, ref turnSmoothVelocity, turnSmoothTime);
            transform.rotation = Quaternion.Euler(0f, angle, 0f);

            moveDir = Quaternion.Euler(0f, targetAngle, 0f) * Vector3.forward;
        }

        if (Input.GetButtonDown("Jump") && controller.isGrounded)
        {
            moveDir.y = jumpSpeed;
        }

        moveDir.y -= gravity * Time.deltaTime;

        controller.Move(moveDir.normalized * characterSpeed * Time.deltaTime);
    }
}

It only lets me jump while the CharacterController is motionless, but I’d like to be able to jump while for example moving forward.

Greetings, @Shreddedcoconut

The problem is that, although you set the moveDir.y in line 37, line 32 uses Vector2.forward, which is (0, 0, 1) so is resetting the Y component every time. That code in line 32 only runs when you are moving (the check is line 26) so that’s why you only get the jump when you are static.

You’ll need to rewrite your code so that you include the jump in your calculation. However, don’t forget that the jump should never go negative. Line 40 would keep on making the player fall and fall, except that it, too, is ignored because you are using Vector3.forward.

Don’t give up. Writing a good character controller is one of the hardest things to do and is different for just about every game. There are so many variations…