Search code examples
c#unity-game-enginephysics

isGrounded not working properly gives double jump


I am trying to get my cube to jump when i press space. But for some reason the isGrounded glitches and i can double jump even when its in the air. and also its very inconsistent like if i spam space a bit it jumps higher or starts rotating the cube. I am a beginner to unity and don't know why. any help appreciated.

I have tried using rb.addForce instead of transform.Translate but that starts rotating the cube when i move it and i want it to glide smoothly on the platform.

My code

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
 
public class PlayerController : MonoBehaviour
{
 
    private Rigidbody rb;
 
    public Vector3 jump;
    public float jumpForce = 2.0f;
    public bool isGrounded;
 
    public float speed = 0;
    private float movementX;
    private float movementY;
    // Start is called before the first frame update
    void Start()
    {
        rb = GetComponent<Rigidbody>();
        jump = new Vector3(0.0f, 2.0f, 0.0f);
    }
 
    void OnMove(InputValue movementValue)
    {
        Vector2 movementVector = movementValue.Get<Vector2>();
        movementX = movementVector.x;
        movementY = movementVector.y;
    }
 
    void OnCollisionStay()
    {
        isGrounded = true;
        Debug.Log("GROUDED");
    }
 
    private void Update()
    {
        if (Keyboard.current.spaceKey.wasPressedThisFrame && isGrounded)
        {
            rb.AddForce(jump * jumpForce, ForceMode.Impulse);
            isGrounded = false;
            Debug.Log("UnGROUNDED");
        }
    }
 
    private void FixedUpdate()
    {
        Vector3 movement = new Vector3(movementX, 0.0f, movementY);
        transform.Translate(movement/speed);
    }
}

Solution

  • Also add void OnCollisionExit:

        private void OnCollisionExit(Collision collision)
        {
            isGrounded = false;
            Debug.Log("UnGROUNDED");
        }
    

    From the Update, you can delete

    isGrounded = false;
    Debug.Log("UnGROUNDED");
    

    To prevent the cube from rotating, check the "Freeze rotation" boxes in the "Constraints"section in Rigidbody:

    enter image description here