I posted a question a few days ago, but haven’t received any responses. I thought I would rephrase my question in hopes of getting some better feedback.
I’m trying to understand my options for flipping sprites horizontally in Unity 2D (specifically version 5.0+). From what I know, there are two main options:
Create sprites for facing right and facing left and switch between them as needed
Create a single sprite for facing one direction and multiply the transform’s localScale by -1 whenever you want to mirror the image
I was using option #2 in Unity 4.X without any problems, but when I upgraded my project to unity 5.0, modifying the localScale made my sprite disappear. Any ideas why that might be the case? Please see the code in question below. If anyone has some efficient alternatives, please let me know.
// Flip sprite / animation over the x-axis
protected void Flip()
{
isFacingRight = !isFacingRight;
Vector3 theScale = transform.localScale;
theScale.x *= -1;
transform.localScale = theScale;
// Flip collider over the x-axis
center.x = -center.x;
}
I think the “proper” method here would be to use localRotation (assuming 2D here right?) and a Quaternion and flip back and forth as needed… Just my quick example but I’m sure you could see how to adapt it. I still don’t fully understand Quaternion’s haha! But this should do the trick for you:
I tried setting the bool variable flipX and flipY but the problem is that the colliders would not flip along with the sprites. This problem would make sense when you use a collider instead of just wrapping it around the character and for something else like wall detection (on collision) in the case of enemy patrolling or when no ground is detected (collision exit case).
if you want to flip the sprite along with the collider then this one worked for me:
transform.localScale = new Vector2(
-transform.localScale.x ,
transform.localScale.y
);
here, you just flip the scale of the sprite on the x-axis and keep the y-axis as it is.
Hope this would help someone.
SpriteRenderer spriteRenderer;
void Start()
{
spriteRenderer = GetComponent<SpriteRenderer>();
FlipSprite();
}
void FlipSprite()
{
if (move < 0)
{
spriteRenderer.flipX = true;
//This is based that your sprite is facing which way
}
else if (move > 0)
{
spriteRenderer.flipX = false;
//Hope this would help
}
}