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
- Create an Animator Controller asset, and add three states:
Idle,Run,Jump. - Add parameters: a
float Speedand abool IsGrounded. - Draw transitions:
Idle → RunwhenSpeed > 0.1,Run → IdlewhenSpeed <= 0.1, and both→ JumpwhenIsGroundedbecomesfalse. - Assign the Animator Controller to the player's
Animatorcomponent.
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
PlayerAnimationscript, separate fromPlayerController's movement logic, means either one can change without touching the other. spriteRenderer.flipXmirrors 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.