# Flip x when direction of the movement changed in Unity

What is the easiest and the most efficient way to flip x of the SpriteRenderer when direction of the movement changed in Unity?

I use Input.GetAxis() in order to get user input. When it returns 0 I would like to do nothing, when it returns positive number I would like to have x flipped in SpriteRenderer in one side and when number returned is negative another side.

So far I come up with a solution of using a variable which will be keeping the info about to which side the player is turned and flip x if necessary. But I am sure that this is not an efficient way to do it and even not a convenient one since my code will tend to become a lot bigger and messier.

• If you're trying to solve a specific instance of messy code, it would be helpful to include that code as a sample. Otherwise we might end up telling you how to fix a completely different kind of mess than the one you have. ;) Jun 17 '17 at 14:49
• @DMGregory, may I edit my question by adding code sample? Jun 17 '17 at 14:56
• You don't need to ask permission. Editing posts to improve them and add clarity is very much encouraged here. :) Jun 17 '17 at 15:07

I suggest do not bind the flipping procedure to the Input since it is directly relevant to the moving direction of the body (Input may not change the body's moving duration in some specific occasions). Do it by simply checking the velocity vector of the rigidBody2D.

It can be simply done by 2 ways:

-Either you can check in the moving object's Update() loop by simply writing:

if(rigidbody2D.velocity.x >= 0){
spriteRenderer.flipX = false;
}
else {
spriteRenderer.flipX = true;
}


- Or you can do the same check whatever the function changes the velocity of the body that you are moving.

You can also simplify the code into one line, if you want less lines like the following:

spriteRenderer.flipX = rigidBody2D.velocity.x < 0 ? true : false;

• Will it work for me if I use Transform.Translate() to move my player? Jun 19 '17 at 10:37
• Yes it will, since transform.Translate() does not change the object's scale or rotation, the sprite renderer will maintain its setting about flipX. Jun 19 '17 at 19:30