I'm new to coding with C# and Unity and I've been having an issue with my first person game, specifically, with my character's jump mechanic. Sometimes the character will jump, sometimes he wont, sometimes he'll do a mini jump, and I don't know what the issue with the code is. I wrote the jump script separately to the rest of the moving mechanics, because frankly, the rest of the movement code is an absolute mess.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Jump : MonoBehaviour
{
private CharacterController controller;
private float verticalVelocity;
private float gravity = 14f;
private float jumpForce = 10f;
private void Start()
{
controller = GetComponent<CharacterController>();
}
private void Update()
{
if(controller.isGrounded)
{
verticalVelocity = -gravity * Time.deltaTime;
if(Input.GetKeyDown(KeyCode.Space))
{
verticalVelocity = jumpForce;
}
}
else
{
verticalVelocity -= gravity * Time.deltaTime;
}
Vector3 moveVector = new Vector3(0, verticalVelocity, 0);
controller.Move(moveVector * Time.deltaTime);
}
}