2D Player Animation (part 3)

Flipping your 2D Player left and right according to direction

If you have noticed from the previous article that when the player moves towards the left the sprite is still facing left. In this article we will remedy that by using Unity’s new method of flipping the sprite left and right according to the direction the player is headed.

Objective: Learn how to flip the 2D Player sprite using Unity’s new Flip function.

As of Unity 2019 and above, Unity has updated the functionality of the Sprite Renderer to include the flip X and Y ability to allow easier access to flip your player.

Player Script:

In the player script we are first going create a handler on the top and get the Sprite Renderer component. Then we need to use the Get component in children to gain access.

Then within the Update method we are going to use and IF and Else IF statement to define the condition on when to flip the player.

First if the Input Horizontal has a value greater than zero, meaning that it is going right, then we don’t need to flip the sprite. Else if the horizontal input is less than zero that means that the player is facing left. Therefore we need to flip the sprite. To flip the sprite we just need to state the sprite Renderer and use “flipX” as the function along with the boolean value of true or false.

Now back in Unity you will see that your player flips once it is facing left and vice versa when facing right again.

Bonus:

Script Optimization:

Now that we have our basics for the character flip, it is time to properly write the script in a more clean and professional method. It is always in best practice to proper you script in a way where you are going to expect other people to read you script. Therefore it is prefer to organized your script in a manner where others can understand your script at just a glance.

What we are going to do is create a true or false boolean that the if statement can read and also making the actual flip function it’s own separate method.

We start with creating a new void method called “Flip” and also give the Boolean value of “Facing Right”.

Then instead of placing the calculations of the flip within the Update method, we are going to move them into the actual “Movement” method so we are allow to use the “movement” variable replacing the Input Horizontal. Then inside the If statement we are going to use the newly created “Flip” method and state whenever the boolean is true or false.

With this, the script should now be a lot more simpler to read and understand, should other people have access to your script.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Simon Truong

Simon Truong

A Designer, an Illustrator and a massive tech geek aspiring to become a professional Unity Developer.