Build a 2D Platformer using Unity and C#

Lesson 4 of 7

Animator: Idle, Run, and Jump Animations

A static sprite makes movement look robotic. Unity's Animator system swaps between animation clips based on parameters your code sets every frame.

Setting up the Animator Controller

  1. Create an Animator Controller asset, and add three states: Idle, Run, Jump.
  2. Add parameters: a float Speed and a bool IsGrounded.
  3. Draw transitions: Idle → Run when Speed > 0.1, Run → Idle when Speed <= 0.1, and both → Jump when IsGrounded becomes false.
  4. Assign the Animator Controller to the player's Animator component.
using UnityEngine;

public class PlayerAnimation : MonoBehaviour
{
    Animator animator;
    Rigidbody2D rb;
    SpriteRenderer spriteRenderer;

    void Awake()
    {
        animator = GetComponent<Animator>();
        rb = GetComponent<Rigidbody2D>();
        spriteRenderer = GetComponent<SpriteRenderer>();
    }

    void Update()
    {
        float speed = Mathf.Abs(rb.linearVelocity.x);
        animator.SetFloat("Speed", speed);
        animator.SetBool("IsGrounded", Mathf.Abs(rb.linearVelocity.y) < 0.01f);

        if (rb.linearVelocity.x != 0f)
        {
            spriteRenderer.flipX = rb.linearVelocity.x < 0f;
        }
    }
}

The pieces

  • animator.SetFloat(...)/SetBool(...) push values from code into the Animator Controller's parameters every frame, the transitions you drew in the editor react to those values automatically, your code never has to say "play the Run animation" directly.
  • Keeping animation logic in its own PlayerAnimation script, separate from PlayerController's movement logic, means either one can change without touching the other.
  • spriteRenderer.flipX mirrors the sprite horizontally, a cheap way to make one "Run" animation face both left and right instead of needing separate clips.

WARNING

If a transition's conditions can never actually be reached (e.g. checking Speed > 0.1 but the code only ever sets whole numbers), the Animator gets stuck in one state. Use the Animator window's live preview during Play mode to watch which state is active and debug transitions.

📝 Animator Quiz

Passing score: 70%
  1. 1.How does code trigger an Animator transition, like Idle to Run?

  2. 2.spriteRenderer.____ mirrors a sprite horizontally, useful for reusing one animation for both facing directions.

  3. 3.Animation logic and movement logic must always live in the same script.