Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

Bug Characters can jump twice, although it checks is character grounded

Discussion in 'Scripting' started by Sasha2009111, Feb 10, 2023.

  1. Sasha2009111

    Sasha2009111

    Joined:
    Apr 1, 2022
    Posts:
    2
    Here is my code:
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. [RequireComponent(typeof(Rigidbody))]
    6. public class PlayerMovementScript : MonoBehaviour
    7. {
    8.     public Vector3 jump;
    9.     public float jumpForce = 2.0f;
    10.  
    11.     public bool isGrounded;
    12.     Rigidbody rb;
    13.     void Start()
    14.     {
    15.         rb = GetComponent<Rigidbody>();
    16.         jump = new Vector3(0f, 2f, 0f);
    17.     }
    18.  
    19.     private void OnCollisionStay(Collision collision)
    20.     {
    21.         isGrounded = true;
    22.     }
    23.  
    24.     void Update()
    25.     {
    26.         if (Input.GetKeyDown(KeyCode.Space) && isGrounded)
    27.         {
    28.             rb.AddForce(jump * jumpForce, ForceMode.Impulse);
    29.             isGrounded = false;
    30.         }
    31.     }
    32. }
    You can jump only two times
     
  2. Brathnann

    Brathnann

    Joined:
    Aug 12, 2014
    Posts:
    7,150
    Are you saying you can jump twice in a row? (ie, tap space twice and it double jumps) or that you can jump once, land, jump a second time, land and then it breaks?
     
  3. Sasha2009111

    Sasha2009111

    Joined:
    Apr 1, 2022
    Posts:
    2
    I jump, then isGrounded turns into false for a moment, then it turns back to true, then i jump again, isGrounded turns into false and it doesn't turns into true until i get on the ground
     
  4. Brathnann

    Brathnann

    Joined:
    Aug 12, 2014
    Posts:
    7,150
    If it's turning back to true, it's because before your jump actually moves your character away from the ground, OnCollisionStay is triggering and turning it back to True would be my guess.

    You can verify this with some Debug calls.
     
  5. kdgalla

    kdgalla

    Joined:
    Mar 15, 2013
    Posts:
    4,382
    Yes, I dealt with a similar problem recently. When the player presses the jump button you are setting isGrounded to false but the character is still on the ground at that point, so your ground check is setting it right back to true.

    In my case, I simply had my script wait a few frames after jumping before it resumed ground checking.
     
    Brathnann likes this.