Flipping 2d character

Welcome, i am learning unity and i need some help. My sprite is ,looking" on its left (your right) by deafult. While i am walking to the left, character is still looking to the right. Can u help me?

using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
    [SerializeField] private float speed;
    private Rigidbody2D body;
    private Animator anim;
    private bool grounded;
   
    private void Awake()
    {  
        //Grabs references for rigidbody and animator from game object.
        body = GetComponent<Rigidbody2D>();
        anim = GetComponent<Animator>();
    }
    private void Update()
    {
        float horizontalInput = Input.GetAxis("Horizontal");
        body.velocity = new Vector2(horizontalInput * speed, body.velocity.y);
        //Flip player when facing left/right.
        if (horizontalInput > 0.01f)
            transform.localScale = Vector3.one;
        else if (horizontalInput < -0.01f)
            transform.localScale = new Vector3(-1, 1, 1);
        if (Input.GetKey(KeyCode.Space) && grounded)
            Jump();
        //sets animation parameters
        anim.SetBool("run", horizontalInput != 0);
        anim.SetBool("grounded", grounded);
    }
    private void Jump()
    {
        body.velocity = new Vector2(body.velocity.x, speed);
        anim.SetTrigger("jump");
        grounded = false;
    }
    private void OnCollisionEnter2D(Collision2D collision)
    {
        if (collision.gameObject.tag == "Ground")
            grounded = true;
    }
}

There are many possible ways to do this.

I do NOT recommend changing scale to negative, even though a lot of demos do it this way. It can have a LOT of complications.

In ALL ways I recommend NEVER flipping the root transform but instead only changing child Transforms.

Here are two possible ways. You only need ONE method:

  1. If you’re using a sprite, just set / clear the .flipX property in the SpriteRenderer:
  1. If you have a hierarchy of sprites or other visuals, I prefer to rotate the hierarchy, changing it to either Quaterion.identity or Quaternion.Euler(0,180,0)

This is possible by structuring your player as:

PivotLeftRight <------- rotate me around the Y axis by 180
VisibleBody
HisWeapon```

3. Swap out the sprite: this requires you to have face left / right sprites.

There are plenty of other approaches, but the above is always the simplest.

Animations CAN be used to accomplish all of these things, but animations can also have complications with them. It's always best to start simple and build up, testing as you go.
2 Likes