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

Jumping by holding space

Discussion in 'Scripting' started by MitjaHD, Mar 15, 2020.

  1. MitjaHD

    MitjaHD

    Joined:
    Sep 30, 2018
    Posts:
    64
    Code (CSharp):
    1. groundCheckPosition = new Vector2(gameObject.transform.position.x, gameObject.transform.position.y - offset);
    2.         grounded = Physics2D.OverlapCircle(groundCheckPosition, 0.15f, groundLayer);
    3.  
    4.         if (Input.GetButton("Jump") && grounded)
    5.         {
    6.             Jump();
    7.         }
    8.  
    9. void Jump()
    10.     {
    11.         rb2d.AddForce(new Vector2(rb2d.velocity.x, jumpForce), ForceMode2D.Impulse);
    12.         grounded = false;
    13.     }
    This code doesn't work well, because sometimes I can jump higher than I should (I think it dedetcs button twice or more). I could change GetButton to GetButtonDown and it would work but then I would need to re-press the space button (I want to hold it and jump once, when I land on the ground).
     
  2. orionsyndrome

    orionsyndrome

    Joined:
    May 4, 2014
    Posts:
    3,043
    you do realize that this way the better your framerate is, the "more" you jump?
     
  3. Serinx

    Serinx

    Joined:
    Mar 31, 2014
    Posts:
    785
    The way you're checking if the character is grounded will AddForce multiple times because the character will be overlapping with the ground for a few frames even after jumping.

    If you're using a Character Controller component, there's a built-in isGrounded property you can use.

    Otherwise, you could tag the "ground" objects with a "ground" tag and use OnCollisionEnter2D/OnCollisionExit2D to set your own "isGrounded" boolean to true when you collide with an object tagged "ground".
     
    Joe-Censored likes this.
  4. MitjaHD

    MitjaHD

    Joined:
    Sep 30, 2018
    Posts:
    64
    And why is that?
     
  5. MitjaHD

    MitjaHD

    Joined:
    Sep 30, 2018
    Posts:
    64
    But I can also hit ground from the front, not only from below, collision would happen and I could jump.
     
  6. orionsyndrome

    orionsyndrome

    Joined:
    May 4, 2014
    Posts:
    3,043
    Is this in your FixedUpdate?
    Code (csharp):
    1. if (Input.GetButton("Jump") && grounded)
    2. {
    3.   Jump();
    4. }
     
    Joe-Censored likes this.
  7. Serinx

    Serinx

    Joined:
    Mar 31, 2014
    Posts:
    785
    True, you could combine this check with your existing check to make sure the collision point is under the player - or check that it's under in some other way.
     
  8. MitjaHD

    MitjaHD

    Joined:
    Sep 30, 2018
    Posts:
    64
    Yes in FixedUpdate