In this tutorial, you will learn how to control player animations in your 2D game with C# code in Unity. Watch the video below and then scroll down for the sample code.
Sample code
using UnityEngine; using System.Collections; public class PlayerController : MonoBehaviour { public float speed = 5f; public float jumpSpeed = 8f; private float movement = 0f; private Rigidbody2D rigidBody; public Transform groundCheckPoint; public float groundCheckRadius; public LayerMask groundLayer; private bool isTouchingGround; private Animator playerAnimation; // Use this for initialization void Start () { rigidBody = GetComponent<Rigidbody2D> (); playerAnimation = GetComponent<Animator> (); } // Update is called once per frame void Update () { isTouchingGround = Physics2D.OverlapCircle (groundCheckPoint.position, groundCheckRadius, groundLayer); movement = Input.GetAxis ("Horizontal"); if (movement > 0f) { rigidBody.velocity = new Vector2 (movement * speed, rigidBody.velocity.y); } else if (movement < 0f) { rigidBody.velocity = new Vector2 (movement * speed, rigidBody.velocity.y); } else { rigidBody.velocity = new Vector2 (0,rigidBody.velocity.y); } if(Input.GetButtonDown ("Jump") && isTouchingGround){ rigidBody.velocity = new Vector2(rigidBody.velocity.x,jumpSpeed); } playerAnimation.SetFloat ("Speed", Mathf.Abs (rigidBody.velocity.x)); playerAnimation.SetBool ("OnGround", isTouchingGround); } }
Next tutorial: Flipping the player with code