Jump Script Problem

The jump code I made for my character is working great, but there’s this little snag: You can do unlimited jumps in the air. I need that gone, and just have only the single jump. Here’s the code:

{
    public CharacterController controller;

    public float Speed = 12f;
    public float gravity = -9.81f;
    public float jumpHeight = 3f;

    public Transform groundCheck;
    public float groundDistance = 0.4f;
        public LayerMask groundMask;

    Vector3 velocity;
    bool isGrounded;

    void Start()
    {
        isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);

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

    }

    void Update()
    {
        float x = Input.GetAxis("Horizontal");
        float z = Input.GetAxis("Vertical");
       
        Vector3 playerMovement = transform.right * x + transform.forward * z;

        controller.Move(playerMovement * Speed * Time.deltaTime);

        if(Input.GetButtonDown("Jump") && isGrounded)
        {
            velocity.y = Mathf.Sqrt(jumpHeight * -2f * gravity);
        }

        velocity.y += gravity * Time.deltaTime;

        controller.Move(velocity * Time.deltaTime);
    }

}

If there are any suggestions, I would appreciate it.

You’re setting “isGrounded” in start and never setting it again. You should be checking if the character is touching the ground in Update before you use isGrounded to see if you can jump or not.

In fact just a quick look at the code I’d assume everything in your Start method is intended to be in your Update method.

Thanks for that bit, Joe. And I also forgot one other thing that made the unlimited jump bug: The Layer Mask. But with that out of the way. I might be able to build my level after a few runs. While I’m doing that, is there a tutorial for targets?

Glad you’re moving forward, but I can’t answer tutorial questions as I haven’t done any recently. Hopefully someone else chimes in.