Toasty
Toasty

Reputation: 1

2D Jumping Animation stuck on loop

I have added the jumping animation to my player. When my player jumps, the animation plays. However when the player lands, the jump animation becomes stuck. When I check the animator tab, the jump animation is just being played on a loop.

This is the Code for the Jumping stuff - Animation/actual movement:

    void Update()
    {
        horizontal = Input.GetAxisRaw("Horizontal");

        animator.SetFloat("Speed", Mathf.Abs(horizontal));

        if (Input.GetButtonDown("Jump") && IsGrounded())
        {
            rb.velocity = new Vector2(rb.velocity.x, jumpingPower);
            jump = true;
            animator.SetBool("isJumping", true);
        }

        if (Input.GetButtonUp("Jump") && rb.velocity.y > 0f)
        {
            rb.velocity = new Vector2(rb.velocity.x, rb.velocity.y * 0.5f);
        }

        if (Input.GetButtonUp("Jump") && IsGrounded())
        {
            animator.SetBool("isJumping", false);
            animator.SetBool("isGrounded", true);
            jump = false;
        }

        Flip();
    }

This should check whether the player is grounded or not:

    private bool IsGrounded()
    {
        return Physics2D.OverlapCircle(groundCheck.position, 0.2f, groundLayer);
    }

Upvotes: 0

Views: 148

Answers (1)

taiyo
taiyo

Reputation: 539

This statement does not what you think it does

if (Input.GetButtonUp("Jump") && IsGrounded())

GetButtonUp returns true the first frame the button is released (see docs). But it will return false again if the button has been released. This is not made that clear in the docs. Or to put it in other words: GetButtonUp returns true in that frame where the button has been released but in the frame before it was still pressed.

You could just detect the moment the player lands to switch animations:

if (jump && IsGrounded()) {  // player just landed
     animator.SetBool("isJumping", false);
     animator.SetBool("isGrounded", true);
     jump = false;
}

Upvotes: 1

Related Questions