How do I Make player face the direction of movement in Unity 2D

I working on a unity 2d game. I currently have this script to move my player. but my player sprite faces the wrong direction. please what do I do here :

 using System;
using UnityEngine;

public class Player : MonoBehaviour
{
    [SerializeField]
    private float _speed = 5.0f; // Speed for player movement

    private Rigidbody2D _rigidbody; // Reference to the Rigidbody2D component

    void Start()
    {
        _rigidbody = GetComponent<Rigidbody2D>(); // Get the Rigidbody2D component
    }

    void Update()
    {
        Movement();
    }

    private void Movement()
    {
        // Handles player movement left or right
        float horizontalInput = Input.GetAxis("Horizontal");
        _rigidbody.velocity = new Vector2(horizontalInput * _speed, _rigidbody.velocity.y);
    }
}
1 Like

Hello, the idea here is to use the transform.localScale. I have added two functions in your code to help with that

using System;
using UnityEngine;

public class Player : MonoBehaviour
{
    [SerializeField]
    private float _speed = 5.0f;

    private Rigidbody2D _rigidbody;
    private bool _facingRight = true; 

    void Start()
    {
        _rigidbody = GetComponent<Rigidbody2D>(); 
    }

    void Update()
    {
        Movement();
        FlipPlayer();
    }

    private void Movement()
    {
        // Handles player movement left or right
        float horizontalInput = Input.GetAxis("Horizontal");
        _rigidbody.velocity = new Vector2(horizontalInput * _speed, _rigidbody.velocity.y);
    }

    private void FlipPlayer()
    {
        // here we are flipping player direction
        float horizontalInput = Input.GetAxis("Horizontal");

        if (horizontalInput > 0 && !_facingRight)
        {
            Flip();
        }
        else if (horizontalInput < 0 && _facingRight)
        {
            Flip();
        }
    }

    private void Flip()
    {
        // Flip the player's local scale to mirror the sprite
        _facingRight = !_facingRight;
        Vector3 localScale = transform.localScale;
        localScale.x *= -1; // turns the player opposit direction
        transform.localScale = localScale;
    }
}
1 Like