Search code examples
unity-game-engineanimation2dtopdown

In 2D animation, the character goes into idle mode when a key is pressed in unity


Instead of animating a character in an inactive(Idle) state.

The B key is pressed here:.

After a while the animation works again:.

Exit time is disabled for transitions.

Player Controller file code:

public class PlayerController : MonoBehaviour
{
    public float moveSpeed;
    public Animator animator;
    Vector2 movement;
    private Rigidbody2D rb;
    // Start is called before the first frame update
    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
    }

    // Update is called once per frame
    void Update()
    {
        movement.x = Input.GetAxisRaw("Horizontal");
        movement.y = Input.GetAxisRaw("Vertical");

        animator.SetFloat("Horizontal", movement.x);
        animator.SetFloat("Vertical", movement.y);
        animator.SetFloat("Speed", movement.sqrMagnitude);
    }
    
    void FixedUpdate() 
    {
        
        rb.MovePosition(rb.position + movement.normalized * moveSpeed * Time.fixedDeltaTime);   
    }
}

Horizontal and Vertical parameters: Animator Window Animator Window

Here are the transitions between the idle state and the running state (Movement): Animator Transition Idle -> Movement Animator Transition Movement-> Idle

After the speed parameter becomes greater than 0.01, the character goes into the running state(Movement), if less than 0.01, back to the idle state.


Solution

  • Your question is not very clear. Please try to rephrase it. I don't see anything in code that changes state on button press. Where are you using the "Horizontal" and "Vertical" parameters?

    May be this Getting started with Unity Animation guide will help you.