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\$
3
  • \$\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
    Commented Jun 17, 2017 at 14:49
  • \$\begingroup\$ @DMGregory, may I edit my question by adding code sample? \$\endgroup\$
    – Yaroslav
    Commented Jun 17, 2017 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
    Commented Jun 17, 2017 at 15:07

1 Answer 1

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;
\$\endgroup\$
2
  • \$\begingroup\$ Will it work for me if I use Transform.Translate() to move my player? \$\endgroup\$
    – Yaroslav
    Commented Jun 19, 2017 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
    Commented Jun 19, 2017 at 19:30

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .