🛠 Problem:
The character doesn’t animate correctly or looks wrong when moving left in previous tutorial: Unity in Practice 0009 – How to Use Sprite Sheets in Unity for 2D Animation and UI – Wonderful Code See
🎯 Solution:
To fix the left run animation that appears incorrect, you generally don’t need a separate animation for left movement. Instead, use sprite flipping to mirror the existing run animation.
To flip the character in Unity when moving left or right, you can Flips the GameObject on the Y-axis to visually mirror it. Here’s how to do it:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BallScript : MonoBehaviour
{
private Rigidbody2D rb;
private Animator playerAnim;
[SerializeField] private float moveSpeed = 5;
[SerializeField] private float jumpForce = 10;
private float xInput;
private bool isRun;
private int facingDirection = 1;
private bool facingRight = true;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody2D>();
playerAnim = GetComponentInChildren<Animator>();
}
// Update is called once per frame
void Update()
{
// Get horizontal input
xInput = Input.GetAxis("Horizontal");
// Apply horizontal movement
rb.velocity = new Vector2(xInput * moveSpeed, rb.velocity.y);
// Jump on Space key press
if (Input.GetKeyDown(KeyCode.Space))
{
rb.velocity = new Vector2(rb.velocity.x, jumpForce);
}
// Flip the player based on input direction
FlipController();
// Animate player running
isRun = rb.velocity.x != 0;
playerAnim.SetBool("IsRun", isRun);
}
private void Flip()
{
facingDirection = facingDirection * -1;
facingRight = !facingRight;
transform.Rotate(0, 180, 0);
}
private void FlipController()
{
if (rb.velocity.x > 0 && !facingRight)
{
Flip();
}
else if (rb.velocity.x < 0 && facingRight)
{
Flip();
}
}
}