Search Unity

Playing animation while moving vertically and horizontally

Discussion in 'Scripting' started by iRuDz, Jan 15, 2017.

  1. iRuDz

    iRuDz

    Joined:
    Feb 1, 2016
    Posts:
    39
    Hey everyone, i'm trying to play a running animation on my mesh when Input.GetAxis(Horizontal) or Input.GetAxis(Vertical) is true. I watched a Youtube video but they only made the animation play when Input.GetAxis(Vertical) is true, now my animation only plays when the "a" key is pressed. How do i make it so that the animation plays when any of the "wasd" keys are pressed using the animator and scripting?
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class PlayerMovement : MonoBehaviour {
    6.  
    7.     //The speed of the player.
    8.     public float playerSpeed;
    9.  
    10.     private float vert;
    11.  
    12.     public Animator playerAnim;
    13.  
    14.     void Start ()
    15.     {
    16.         playerAnim = GetComponent<Animator>();
    17.     }
    18.  
    19.     void Update ()
    20.     {
    21.         //The movement of the player.
    22.         transform.Translate(Input.GetAxis("Horizontal") * playerSpeed * Time.deltaTime, 0f,
    23.             Input.GetAxis("Vertical") * playerSpeed * Time.deltaTime);
    24.  
    25.         //Plays the "run" animation while the wasd keys are pressed.
    26.         vert = Input.GetAxis("Vertical");
    27.         playerAnim.SetFloat("run", vert);
    28.     }
    29. }
     
  2. supermoof

    supermoof

    Joined:
    Sep 24, 2015
    Posts:
    45
    Your mecanim is probably checking the vert float that you are setting with SetFloat. Just do:

    Code (csharp):
    1.  
    2. horizontal = Input.GetAxis("Horizontal");
    3.  
    Send the horizontal into your mecanim and have your mecanim also do the animation if horizontal changes as well.
     
  3. iRuDz

    iRuDz

    Joined:
    Feb 1, 2016
    Posts:
    39
    I don't really understand. Should i make a variable called horizontal? and how do i send it to my mecanim?