Buggy Unity "jump" mechanic

Viewed 122

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);
}
}
1 Answers

If you have 2 scripts that use use controller.Move() that is certainly going to cause some issues. You need 1 script to move the CharacterController

The most practical way to do this in my opinion is have a Vector3 variable for moveX, moveY, and moveZ. Add them up after the calculations and use that for controller.Move(). Heres an example of what I'm saying:

direction = Vector3.zero;
moveX = transform.right * Input.GetAxis("Horizontal") * speed;
moveY = new Vector3(0, vely, 0);
moveZ = transform.forward * Input.GetAxis("Vertical") * speed;

direction = moveX + moveY + moveZ;

controller.Move(direction * Time.deltaTime);

Somewhere in here you could add the jump feature by modifying vely or moveY in some way.

Related