[Unity] 2D Sprite Flipping

Tom GrzembkeTom Grzembke
2 min read

I searched for an alternative to flipping sprites in a sidescroller environment and wasn't that happy with my findings.

To flip the sprite, my script uses the x scale to blend the character's start x-axis to its negative counterpart in the context of the rigid body input.

Explanation

The Inspector allows us to control a few parameters:

TimeToFlip: How long the sprite will take to flip in seconds
Flip Curve: The curve progress of the flip
Flip Sensitivity: All rb.velocity.magnitude under this will be ignored
Rb: Slot for the RigidBody

Code

Aaand here's the code behind it,
here's a good block on AnimationCurves in case you need it!

using System.Collections;
using UnityEngine;

public class FlipObjectWithVelocity : MonoBehaviour
{
    #region serialized fields
    [SerializeField] float timeToFlip = .3f;
    [SerializeField] AnimationCurve flipCurve = AnimationCurve.EaseInOut(0,0,1,1);
    [SerializeField] float flipSensitivity;
    [SerializeField] Rigidbody2D rb;
    #endregion

    #region private fields
    Vector3 localScale;
    Vector3 targetScale;
    bool flipState;
    float maxScale;
    Coroutine flipRoutine;
    #endregion

    void Awake() =>  maxScale = transform.localScale.x;

    void Update() => FlipLogic();

    void FlipLogic()
    {
        if (rb.velocity.magnitude <= flipSensitivity) return;

        if (flipRoutine == null)
            flipRoutine = StartCoroutine(Flip());
    }

    IEnumerator Flip()
    {
        flipState = rb.velocity.x > 0;
        localScale = transform.localScale;
        targetScale = localScale;
        targetScale.x = flipState ? -maxScale : maxScale;

        float flipTime = 0;

        while (timeToFlip > flipTime)
        {
            flipTime += Time.deltaTime;
            transform.localScale = Vector3.Lerp(localScale, targetScale, 
            flipCurve.Evaluate(flipTime / timeToFlip));

            yield return null;
        }

        flipRoutine = null;
    }
}

My Use Case

I'm utilizing it with a pixel shader I got from this blog to get scaling pixel sprite flipping.
It's using the same sprite as the gif prior.
Let me know if you are interested in a few hacks I learned while using it!

Thanks

You've come to the end of this post!
I developed this script for my game Qinu, click here to play for free!
Thanks for reading, take care!

0
Subscribe to my newsletter

Read articles from Tom Grzembke directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Tom Grzembke
Tom Grzembke