How to create the Animations (Idle & Walk) in Unity 2D
In this lesson about developing 2D games using Unity, we will focus on generating animations and configuring the animator for our player. Initially, our objective is to produce two animations: one for the idle state and another for running. Once we have created these animations, we can proceed to set up the animator for the player and establish transitions between the animations. Lastly, we will modify the parameters of our animator through some code added to our player controller script, enabling automatic animation transitions.
First thing you need to do is open up Window → Animation → Animation
Next is you’ll see a button that allows you to Create a new animation and you just have to click on that and perhaps create a new folder “Animations” inside your Assets folder and save this file as “Idle”
Then you just need the add the code script below. Create a new file under Scripts folder called OOT_PlayerController.cs and just copy & paste the code below.
OOT_PlayerController.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
public class AU_PlayerController : MonoBehaviour
{
//Components
Rigidbody myRB;
Transform myAvatar;
Animator myAnim;
//Player movement
[SerializeField] InputAction WASD;
Vector2 movementInput;
[SerializeField] float movementSpeed;
private void OnEnable()
{
WASD.Enable();
}
private void OnDisable()
{
WASD.Disable();
}
// Start is called before the first frame update
void Start()
{
myRB = GetComponent<Rigidbody>();
myAvatar = transform.GetChild(0);
myAnim = GetComponent<Animator>();
}
// Update is called once per frame
void Update()
{
movementInput = WASD.ReadValue<Vector2>();
if (movementInput.x != 0)
{
myAvatar.localScale = new Vector2(Mathf.Sign(movementInput.x), 1);
}
myAnim.SetFloat("Speed", movementInput.magnitude);
}
private void FixedUpdate()
{
myRB.velocity = movementInput * movementSpeed;
}
}