Home > Enterprise >  How to flip character when moving left unity 2D
How to flip character when moving left unity 2D

Time:04-20

I am trying to flip my character sprite when moving left in my game, and I have followed multiple tutorials however my sprite does not seem to flip. It is always facing the same way.

Below is my code for my character's movement. I have created a Flip() function and 2 if statements used to call the function. The character can move left, right, up and down (no jumping).

I cannot seem to see where an error would be and why it is not flipping, so any help would be appreciated. thank you.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerMovement : MonoBehaviour
{
    // Start is called before the first frame update

    private Animator animate;
    public float moveSpeed = 6f;
    bool facingRight = true;
    public Rigidbody2D rb;

    Vector2 movement;

    private void Start()
    {
        animate = gameObject.GetComponent<Animator>();
    }

    // Update is called once per frame
    void Update()
    {
        movement.x = Input.GetAxisRaw("Horizontal");
        movement.y = Input.GetAxisRaw("Vertical");
        animate.SetFloat("Speed", Mathf.Abs(movement.x));

        if(movement.x < 0 && facingRight)
        {
            Flip();
        }
        else if (movement.x > 0 && !facingRight)
        {
            Flip();
        }
        
    }

    void FixedUpdate()
    {
        rb.MovePosition(rb.position   movement * moveSpeed * Time.fixedDeltaTime);
        
       
    }

    void Flip()
    {
        Vector3 currentScale = gameObject.transform.localScale;
        currentScale.x *= -1;
        gameObject.transform.localScale = currentScale;

        facingRight = !facingRight;
    }
}

CodePudding user response:

Try to set the flipX property of the SpriteRenderer.

GetComponent<SpriteRenderer>().flipX = true;

You have an animator attached to the game object, if the scale value is controlled by the animation clip, you cannot change it. A typical workaround is give the game object an empty parent and change its scale.

Player    <---- Change scale here
    Model <---- Animator here

CodePudding user response:

transform.Rotate(0f, 180f, 0f); you have to change y while fliping

will work better instead of using currentScale.x *= -1; gameObject.transform.localScale = currentScale;

This code worked for me

private void Flip()
{
    // Rotate the player
    if (transform.localEulerAngles.y != 180 && !facingRight)
        transform.Rotate(0f, 180f, 0f);
    else if(transform.localEulerAngles.y != 0 && facingRight)
            transform.Rotate(0f, -180f, 0f);

    // player flip point of attck also flip is direction
    //transform.Rotate(0f, 180f, 0f);
}
  • Related