Search code examples
c#unity-game-engineanimationmobilesprite

Can't flip sprite using Mobile Input


I am currently working on porting my original project from PC version to mobile, I need help flipping sprite whenever I move left using mobile input, and flip right when I move right. Please help, im losing my mind, i'm sure it's easy but im missing something. I cant find a place to put my Flip() function

My code right now for movement using mobile input.

using System.Collections.Generic;
using UnityEngine;

public class PlayerMovement : MonoBehaviour
{
    public float speed;
    private Rigidbody2D myRB;

    private Vector2 moveAmount;
    private Animator myAnim;
    private bool facingRight = true;

    public Joystick joystick;


    private void Start()
    {
        myAnim = GetComponent<Animator>();
        myRB = GetComponent<Rigidbody2D>();
    }


    private void Update()
    {
        Vector2 moveInput = new Vector2(joystick.Horizontal, joystick.Vertical);
        moveAmount = moveInput.normalized * speed;

        if (moveInput != Vector2.zero)
        {
            myAnim.SetBool("isRunning", true);
        }
        else 
        {
            myAnim.SetBool("isRunning", false);
        }
    }

    private void FixedUpdate()
    {
        myRB.MovePosition(myRB.position + moveAmount * Time.fixedDeltaTime);
    }

    void Flip()
    {
        facingRight = !facingRight;
        Vector3 Scaler = transform.localScale;
        Scaler.x *= -1;
        transform.localScale = Scaler;
    }
}

Solution

  • No idea if your Flip method will do as you expect but logic-wise you can just call Flip if the horizontal direction doesn't match the facing:

    private void Update()
    {
        Vector2 moveInput = new Vector2(joystick.Horizontal, joystick.Vertical);
        moveAmount = moveInput.normalized * speed;
    
        if (moveInput != Vector2.zero)
        {
            myAnim.SetBool("isRunning", true);
        }
        else 
        {
            myAnim.SetBool("isRunning", false);
        }
    
        if ( (facingRight && moveAmount.x < 0) 
          || (!facingRight && moveAmount.x > 0))
        {
            Flip();
        }
    }