简体   繁体   中英

JumpCount resets immediately after jumping 2D platformer

I'm pretty new to all of this so sorry for rookie mistakes. I'm making a 2D platformer I am checking for ground via RayCast and right after the player jumps, the jumpCounter resets to 0, so I get a bonus jump. I tried adding a 0.2s timer before it can reset but that caused trouble when jumping multiple times in a row (bunny hopping). Any help?

private void FixedUpdate()
    {
        GroundCheck();
        if (state != State.hurt)
        {
            Movement();
            DoubleJump();
            StateMachine();
        }

        HurtCheck();
        anim.SetInteger("state", (int)state);
    }
    private void Movement()
    {
        //Input.GetAxis returns a value between -1 up to 1
        //Edit> Project Settings> Input> Axis> Horizontal
        float hDirection = Input.GetAxisRaw("Horizontal");

        //holding down "D" makes the value positive and vice versa
        if (hDirection < 0)
        {
            rb.velocity = new Vector2(-speed, rb.velocity.y);
            transform.localScale = new Vector2(-1, 1);
        }
        else if (hDirection > 0)
        {
            rb.velocity = new Vector2(speed, rb.velocity.y);
            transform.localScale = new Vector2(1, 1);
        }
        else
        {

        }

        if (Input.GetButtonDown("Jump") && isGrounded == true)
        {
            Jump();
        }
    }
    private void Jump()
    {
        rb.velocity = new Vector2(rb.velocity.x, jumpforce);
        state = State.jumping;
        jumpCount += 1;
    }
    private void GroundCheck()
    {
        Debug.DrawRay(transform.position, Vector2.down * hitDistance, Color.green);
        RaycastHit2D hit = Physics2D.Raycast(transform.position, Vector2.down, hitDistance, ground);
        if(hit.collider != null)
        {
            isGrounded = true;
            jumpCount = 0;
        }
        else
        {
            isGrounded = false;
        }
    }
    private void DoubleJump()
    {
        if (Input.GetButtonDown("Jump") && isGrounded == false && jumpCount < 2)
        {
            rb.velocity = new Vector2(rb.velocity.x, jumpforce);
            jumpCount += 1;
        }
    }

Hey Have you made sure your player's layer isn't ground layer or set ground layermask properly or maybe the hitDistance for the raycast is too high it should be very low like 0.1 or less or does jumpCount start from 0 or 1 try and alternate that or maybe have it start from two to lose the extra bonus jump...These would be where I would look, Good luck!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM