Search code examples
unity-game-engineanimationparametersanimationcontroller

Animator parameter doesnt change Unity2D


Hello

I was trying to add an animation transition to my character so have written some code:

void Update()
    {
        Vector3 characterScale = transform.localScale;
        if (Input.GetKey(KeyCode.A))
        {
            animator.SetFloat("speed", velocity);
            characterScale.x = 1;
            transform.Translate(Vector2.right * Time.deltaTime * velocity);
        }
        else animator.SetFloat("speed", 0);


        if (Input.GetKey(KeyCode.D))
        {
            animator.SetFloat("speed", velocity);
            characterScale.x = 1;
            transform.Translate(Vector2.right * Time.deltaTime * velocity);
        }
        else animator.SetFloat("speed", 0);
        

        if (Input.GetKeyDown(KeyCode.Space) && Cground == true)
        {
            rb.AddForce(new Vector2(0f, jumpheight), ForceMode2D.Impulse);
            Cground = false;
        }
        transform.localScale = characterScale;
    }

heres my animation controller: enter image description here

enter image description here

The Problem

My problem is that the speed parameter will only work with the animation transition when walking to the right by pressing D. if i then press A to walk to the left my character sprite flips, he moves but he wont transition to the run animation. I have no idea why and i would be very happy for any help =).


Solution

  • Your problem are the else cases!

    Think about what happens if you only press A: Then you are not pressing D.

    Which means the last thing you do is

    else animator.SetFloat("speed", 0);
    

    so resetting the speed you just had changed for the A press.


    You should rather change your checks to e.g.

    if (Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.D))
    {
        animator.SetFloat("speed", velocity);
        characterScale.x = 1;
        transform.Translate(Vector2.right * Time.deltaTime * velocity);
    }
    else 
    {
        // Only do this if none of the move keys is pressed
        animator.SetFloat("speed", 0);
    }
    

    since apparently anyway you do the se in both cases.

    Or actually I thought you would rather move to the other direction when pressing A.

    Then I would still do

    if (Input.GetKey(KeyCode.A))
    {
        animator.SetFloat("speed", velocity);
        characterScale.x = 1;
        transform.Translate(Vector2.left * Time.deltaTime * velocity);
    }
    else if (Input.GetKey(KeyCode.A))
    {
        animator.SetFloat("speed", velocity);
        characterScale.x = 1;
        transform.Translate(Vector2.right * Time.deltaTime * velocity);
    }
    else 
    {
        animator.SetFloat("speed", 0);
    }