Jumping Problem.

Hi. I have a bit of a jumping problem. whenever press jump the character won’t jump bit instead “deactivates” gravity so hi won’t fall or jump.

here is my code I can’t find what may cause it. the problem first showed up when I added the if statement

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

public class PlayerMovment : MonoBehaviour
{
   
    public CharacterController controller;
    public float speed = 6f;
    public float gravity = 9.12f;
    public float jumpHeight = 3f;

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


    Vector3 velocity;
    bool isGrounded;

    // Update is called once per frame
    void Update()
    {
        isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);

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


        float x = Input.GetAxis("Horizontal");
        float y = Input.GetAxis("Vertical");

        Vector3 move = transform.right * x + transform.forward * y;

        controller.Move(move * speed * Time.deltaTime);

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

        velocity.y -= gravity * Time.deltaTime;

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

I think you are messing up yourself for a simple thing like jumping. I didn’t test your code but it seems that you are trying to control gravity too? If i understanded you use this line “velocity.y -= gravity * Time.deltaTime” to push down the character like gravity does? If yes you don’t need that because Unity already applies physic like this so if you put a rigid body to your character it will depends on physics so when it’s in air it will go down automatically. You shouldn’t use transform to move your character because you will have problems with collisions too, use rigid body instead. With rigid body you will only need

  • if (Input.GetButtonDown(“Jump”) && isGrounded)
  • {
  • Debug.Log(“jumping”);
  • velocity.y = jumpHeigth;
  • }

Also don’t use rigid body inside Update(), use FixedUpdate()

Thanks for the help. I was watching one of Brakeyes videos from oct last year but I still did not get it to work but now it does

velocity.y -= gravity * Time.deltaTime;

I think this line effectively nullifies gravity effect, isn’t it?