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. Dismiss Notice

Question How to fix an infinite jump

Discussion in 'Scripting' started by PanicMedia, May 27, 2021.

  1. PanicMedia

    PanicMedia

    Joined:
    Dec 6, 2020
    Posts:
    37
    I'm currently working on a platformer and for some reason my game has an infinite jump. How do I fix this, so that the player can just double jump instead of being able to jump indefinitely? Here's the code I used
    Code (CSharp):
    1. void Jump()
    2.    {
    3.        Debug.Log("Jump");
    4.        rb.velocity = Vector2.up * jumpForce;
    5.    }
     
  2. Johan_Liebert123

    Johan_Liebert123

    Joined:
    Apr 15, 2021
    Posts:
    474
    Try make a JumpCount, so everytime it jumps the JumpCount = JumpCount + 1, and if it reaches 2, jump = false until it is grounded again. I assume that is what you want
     
  3. Lekret

    Lekret

    Joined:
    Sep 10, 2020
    Posts:
    272
    Make jump counter. I should work like this:
    Code (CSharp):
    1. private int jumpCounter;
    2.  
    3. private void Jump()
    4. {
    5.     if (jumpCounter == 0)
    6.         return;
    7.  
    8.     Debug.Log("Jump");
    9.     rb.velocity = Vector2.up * jumpForce;
    10.     jumpCounter--;
    11. }
    The next part is not that easy, you need to detect the moment your player is touching the ground and reset counter to 2. The easiest way would be raycast, but it's not so reliable, becaue raycast is checking the line, but what if your character is standing on the edge? Triple raycast? It's not so reliable.

    Since your game is 2D and 2D engine in Unity suddenly has a bit more options than 3D, you can use RigidbodyCast, it will simulate attached collider in the direction you want and return results:
    https://docs.unity3d.com/ScriptReference/Rigidbody2D.Cast.html

    If shortly, you do it every FixedUpdate, iterate through buffer in for-loop from 0 to result Cast returned, then if any buffer.normal.y is more than 0.7f, meaning that normal vector is pointing almost up, player IsGrounded and you can reset jumpCount to 2. It's a bit advanced if you are new to Unity, but the result will be better.
     
  4. BuyAnElefant

    BuyAnElefant

    Joined:
    Mar 9, 2021
    Posts:
    8
    I've created for my character child object with small trigger collider under characters feet. And when it hits platform\ground colliders in On2DTriggerEnter method i'm making bool isAbleToJump true. If jump counter is >= 2, than bool isAbleToJump = false. Maybe not the best way to make it but its quite easy
     
    Kurt-Dekker and Lekret like this.