Can someone help me get my Unity 2D character to flip in both directions?

42 Views Asked by At

I have been following a tutorial and when I got to this part, I was stumped. I don't know why this code isn't making my sprite flip in both directions. When I flip once, they get stuck facing to the left, but I can still run and jump.

public class PlayerController : MonoBehaviour
{
    public float moveSpeed;
    public Rigidbody2D theRB;
    public float jumpForce;

    private bool isGrounded;
    public Transform groundCheckPoint;
    public LayerMask whatIsGround;

    private bool canDoubleJump;

    private Animator anim;
    private SpriteRenderer theSR;

    private void Start()
    {
        anim = GetComponent<Animator>();
        theSR = GetComponent<SpriteRenderer>();
    }

    private void Update()
    {
        isGrounded = Physics2D.OverlapCircle(groundCheckPoint.position, .2f, whatIsGround);

        if (isGrounded)
        {
            canDoubleJump = true;
        }

        if (Input.GetButtonDown("Jump"))
        {
            if (isGrounded)
            {
                theRB.velocity = new Vector2(theRB.velocity.x, jumpForce);
            }
            else
            {
                if (canDoubleJump)
                {
                    theRB.velocity = new Vector2(theRB.velocity.x, jumpForce);
                    canDoubleJump = false;
                }
            }
        }
    }

    private void FixedUpdate()
    {
        float horizontalInput = Input.GetAxis("Horizontal");

        // Apply horizontal movement only when grounded
        if (isGrounded)
        {
            theRB.velocity = new Vector2(moveSpeed * horizontalInput, theRB.velocity.y);
        }

        // Flip the character sprite based on the movement direction
        if (horizontalInput < 0)
        {
            theSR.flipX = true;
        }
        else if (horizontalInput > 0)
        {
            theSR.flipX = false;
        }

        anim.SetFloat("moveSpeed", Mathf.Abs(theRB.velocity.x));
        anim.SetBool("isGrounded", isGrounded);
    }
}

I've tried a few different methods, tried some YouTube tutorials, ChatGpt, and my buddy is helping me, but this is a real headscratcher. The Sprite's animations are all playing fine, the colliders appear to be working as intended, I've gone back through the tutorials to make sure I was doing them right. Can someone help me here?

1

There are 1 best solutions below

0
Restu On

Rather than use like this.

...
if (horizontalInput < 0)
{
   theSR.flipX = true;
}
else if (horizontalInput > 0)
{
   theSR.flipX = false;
}
...

Better like this

...
if (moveSpeed > 0)
   theSR.flipX = horizontalInput < 0;
...

Also, I never get input like Horizontal or Vertical in FixedUpdate. I put them on Update.