Home > Back-end >  Unity Jump Script Issue
Unity Jump Script Issue

Time:12-29

I'm new to unity and trying to make a character that can move, jump, etc. However, the jump isn't quite working correctly. The height of the jump seems to change every time, as well as the character falling very slowly after jumping. I can't figure out why it is doing this. My code is as shown below:

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

public class playerMovement : MonoBehaviour
{
    private CharacterController characterController;

    [SerializeField]
    float movementSpeed = 5.0f;
    [SerializeField]
    float jumpHeight = 10.0f;

    float gravity = -9.81f;

    Vector3 relativeMovementInput;
    Vector3 relativeMovement;

    void Start()
    {
        characterController = GetComponent<CharacterController>();
    }

    void Update()
    {
        handleRotation();
        handleMovementInput();
        handleGravity();
        handleJump();

        characterController.Move(relativeMovement * Time.deltaTime);

    }

    void handleGravity()
    {
        if (characterController.isGrounded && relativeMovementInput.y < 0)
        {
            relativeMovement.y = -0.01f;
        }

        relativeMovement.y  = gravity * Time.deltaTime;

    }

    void handleMovementInput()
    {
        float horizontalInput = Input.GetAxis("Horizontal");
        float verticalInput = Input.GetAxis("Vertical");

        Vector3 relativeVerticalInput = transform.forward * verticalInput;
        Vector3 relativeHoriztonalInput = transform.right * horizontalInput;

        relativeMovementInput = relativeHoriztonalInput   relativeVerticalInput;


        relativeMovement.x = relativeMovementInput.x * movementSpeed;
        relativeMovement.z = relativeMovementInput.z * movementSpeed;
    }

    void handleJump()
    {
        bool isJumpPressed = Input.GetButton("Jump");
        bool canJump = characterController.isGrounded;

        if (isJumpPressed && canJump)
        {
            relativeMovement.y  = jumpHeight;
        }

    }

    void handleRotation()
    {
        transform.Rotate(Vector3.up * Input.GetAxis("Mouse X"));
    }
}`

CodePudding user response:

I recomend you to add a rigid body component to your player, it will do all the gravity part. Then you only have to use addforce to make the player jump

CodePudding user response:

First of all, why your character is falling so slowly:

Notice that you multiplied your gravity by Time.deltaTime both in the HandleGravity() method and the update method. You should only multiply it once.

For why the jump height is different, you may be reapplying the jump multiple times. I don't know how you do your ground check, but if the ground check is not precise and would return true if your character is close to the ground, this may be the issue. If the jump is reapplied several frames in a row, this may cause it to be an unexpected height.

  • Related