Daily Progression: Player Facing Left!
Objective: Control, through code, the ability for the player to face left when moving left, and right when moving right!
In our last tutorial we implemented running animation. The animation looks great, until we run to the left. Our player runs backwards when running left. To fix this we need to flip the sprite. Select your sprite object and in the inspector you will see an option to flip X, or Y.
When X is true (checked) the sprite is flipped along the x axis and the player is facing the left, and when the x is false (unchecked) the sprite is facing right again.
We want to control this flip function through code. Open the player script and we need a reference to the sprite objects’ sprite renderer component.
We now want to create a new method, named flip with a bool parameter.
We want to control two scenarios, if the bool is true, and if the bool is false.
If our parameter “faceRight” is true, we want the flip X to be false (meaning our sprite will face to the right)
Also, if the parameter “faceRight” is false, we want the flip X to be true (meaning our sprite will face to the left)
When do we want to call this method? In our movement method we want a set of if and else if statements. Our sprite will face left when our local float variable that represents our player movement is -1, (meaning we are moving to the left) This means when our player movement is -1 we want to call the flip method with a true parameter.
When we move to the right the movement variable is 1, when our movement is 1 we want to call the flip method with a false parameter.
Now when you play the unity editor your player will face the appropriate direction! Don’t be afraid to experiment with your code and I’ll see you in the next tutorial!