Home > Blockchain >  (Unity) Trouble making Double Jump 2d using IF statements
(Unity) Trouble making Double Jump 2d using IF statements

Time:02-17

As the title suggests, I am trying to make a double jump in my Character Controller. The problem is, that using my code the character makes one big jump instead of making a second one.

Here is my code:

        if (m_Grounded && jump)
        {
            // Add a vertical force to the player.
            m_Grounded = false;
            m_Rigidbody2D.AddForce(new Vector2(0f, m_JumpForce));
            canDoubleJump = true;

        } else if (canDoubleJump)
        {
            m_Rigidbody2D.AddForce(transform.up * m_Thrust, ForceMode2D.Impulse);
            canDoubleJump = false;
        }

the defined variables are:

bool canDoubleJump;
public float m_Thrust = 200f;
[SerializeField] private float m_JumpForce = 400f;  

What I have tried so far:

I tried adding the same Vector2 jumpForce in to the double jump place, but then it's just one giant jump even bigger than right now.

I tried changing else if to

else if (canDoubleJump && Input.GetButtonDown("Jump"))

Nothing seems to work. All ideas are appreciated <3

CodePudding user response:

What does the jump variable do? Because this entire if statement needs to be inside another one that goes like

if(Input.GetButtonDown("Jump"))
{

That way there is no chance of it being pressed twice in case you did the jump condition the wrong way.

If that doesn't work or if that's already how it is set up, try adding this to the else if condition

} else if (canDoubleJump && ! m_Grounded)

I'm just throwing in ideas as I'm confused why it's not working as-is.

CodePudding user response:

Your code is not very clear but you can use this code it works fine for me When the jump is called the first time, it jumps once and when it is called and the player doesn't touch the ground, it only jumps one more jump

public Rigidbody2D m_Rigidbody2D;
public float m_Thrust = 400;
public bool isGrounded;
public bool TowJump;
void OnCollisionEnter2D(Collision2D collision)
{
    if (collision.gameObject.tag == "Ground"){
        isGrounded = true;
        TowJump = false;
    }
}
void OnCollisionExit2D(Collision2D collision)
{
    if (collision.gameObject.tag == "Ground"){
        isGrounded = false;
    }
}
public void Jumped()
{
    if(TowJump == false && isGrounded == false)
    {
        m_Rigidbody2D.AddForce(transform.up * m_Thrust, ForceMode2D.Impulse);
        TowJump = true;
    }
    if(isGrounded == true)
    {
        m_Rigidbody2D.AddForce(transform.up * m_Thrust, ForceMode2D.Impulse);
    }
}

Note, you must tag the floor with the name "Ground"

  • Related