Player Animations - Part 3 (Coding the animations)

2D Game Design with Unity

🕑 This lesson will take about 8 minutes

In the previous two lessons, we looked at how to create 2D animations for your player GameObject in Unity on a timeline (using sprites and sprite sheets), and how to configure the transitions between the different animations using the Animator. In this lesson, we will look at how to control when each of these animations plays using code written in the C# programming language. We will add this code to the existing ‘PlayerController.cs’ script created in earlier lessons in this course.

These are the three steps involved in creating player animations:

  1. Create each of the player animations

  2. Configure the animations in the Animator

  3. Control when the animations play with C# code (this lesson)

Game art, tiles and sprites from the Free Pixel Space Platform pack are used in this lesson video and can be downloaded from the Unity Asset Store.

Is YouTube blocked at school? Watch on Google Drive.

Sample code

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
public float speed = 5f;
public float jumpSpeed = 8f;
private float direction = 0f;
private Rigidbody2D player;
public Transform groundCheck;
public float groundCheckRadius;
public LayerMask groundLayer;
private bool isTouchingGround;
private Animator playerAnimation;
// Start is called before the first frame update
void Start()
{
player = GetComponent<Rigidbody2D>();
playerAnimation = GetComponent<Animator>();
}
// Update is called once per frame
void Update()
{
isTouchingGround = Physics2D.OverlapCircle(groundCheck.position, groundCheckRadius, groundLayer);
direction = Input.GetAxis("Horizontal");
if (direction > 0f)
{
player.velocity = new Vector2(direction * speed, player.velocity.y);
}
else if (direction < 0f)
{
player.velocity = new Vector2(direction * speed, player.velocity.y);
}
else
{
player.velocity = new Vector2(0, player.velocity.y);
}
if (Input.GetButtonDown("Jump") && isTouchingGround)
{
player.velocity = new Vector2(player.velocity.x, jumpSpeed);
}
playerAnimation.SetFloat("Speed", Mathf.Abs(player.velocity.x));
playerAnimation.SetBool("OnGround", isTouchingGround);
}
}

Next lesson: Making the player look left and right