0
\$\begingroup\$

My problem is, I have walk animations which only play when my character is moving upward or downward, and I don't know why. This is my code:

public float speed = 5f;
private Animator anim;

void Start () {
    anim = gameObject.GetComponent <Animator>();
}

void Update () {
    anim.SetFloat ("Speed", Mathf.Abs (Input.GetAxis ("Horizontal")));
    anim.SetFloat ("Speed", Mathf.Abs (Input.GetAxis ("Vertical")));

    if (Input.GetAxis ("Horizontal") < -0.1f) {
        transform.localScale = new Vector3 (-1,1,1);
    }
    if (Input.GetAxis ("Horizontal") > 0.1f) {
        transform.localScale = new Vector3 (1,1,1);
    }
}

void FixedUpdate {
    Vector3 move = new Vector3 (Input.GetAxis("Horizontal"), Input.GetAxis ("Vertical"),0);
    transform.position += move*speed*Time.deltaTime;
}
\$\endgroup\$
3
\$\begingroup\$

You're overwriting

anim.SetFloat ("Speed", Mathf.Abs (Input.GetAxis ("Horizontal")));

with

anim.SetFloat ("Speed", Mathf.Abs (Input.GetAxis ("Vertical")));

So only vertical movement is taken into account. To fix it, you can try this

anim.SetFloat("Speed",
              Mathf.Max(Mathf.Abs(Input.GetAxis("Horizontal")),             
                        Mathf.Abs(Input.GetAxis("Vertical"))
              )
);
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.