1 Line of Code and your 2D-Player will Look Where It’s Going
Objective: make a 2D (sprite) character look in the same direction of its motion
You have an animated sprite, your character. You make it move. You make it run or walk. And jump. All with a corresponding animation which is a series of sprites.
But wait! when you move right, it is ok. When you move left… it’s like moon-walking.
Well, you know what? It’s that your character is just a sprite. You have to tell it to look at the motion direction. Here is how to do it in just one line of code, which is highly reusable for other animations.
Let’s say you have those animations and transitions between them. Let’s select one of them and add a state machine behaviour.
Here is the one line of code. On entering the state, we grab a reference to the sprite renderer component. It has two boolean properties, flipX and flipY, which we can set with Velocity.x ≥ 0 statement. By acting only on state entering, we’re going to leave the sprite modified on exiting it, so if we move left and then stop, the character will remain facing left.
All you need to do now is to attach the state machine behaviour to whichever state needs this feature.
If you liked it, clap to it! Check out my games or buy me a coffee: every kind of support is appreciated!!