1
\$\begingroup\$

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.

\$\endgroup\$
  • \$\begingroup\$ 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. ;) \$\endgroup\$ – DMGregory Jun 17 '17 at 14:49
  • \$\begingroup\$ @DMGregory, may I edit my question by adding code sample? \$\endgroup\$ – Yaroslav Jun 17 '17 at 14:56
  • \$\begingroup\$ You don't need to ask permission. Editing posts to improve them and add clarity is very much encouraged here. :) \$\endgroup\$ – DMGregory Jun 17 '17 at 15:07
1
\$\begingroup\$

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;
| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ Will it work for me if I use Transform.Translate() to move my player? \$\endgroup\$ – Yaroslav Jun 19 '17 at 10:37
  • \$\begingroup\$ Yes it will, since transform.Translate() does not change the object's scale or rotation, the sprite renderer will maintain its setting about flipX. \$\endgroup\$ – Tolga Şen Jun 19 '17 at 19:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.