Tilevania flip sprite facing question

Hello,

In the Tilevania project Rick flips sprites on the x axis using its local scale. He uses code

transform.localScale = new Vector2(-(MathF.Sign(myRigidbody.velocity.x)), 1f);

Is there a reason MathF.Sign is used instead of using:

transform.localScale = new Vector3(-transform.localScale.x, 1f);

Both flip the sprite and act as expected. Not sure if this is a standard convention or Rick’s preference.

edit For reference, Rick used the MathF.Sign originally in the player movement as we are collecting input and don’t know what direction the player was heading. So it made sense to pull out the sign and use it. But with the Enemy we are just saying “if you hit a wall, turn around.” Pulling the sign doesn’t seem necessary unless there is some case I am missing.

1 Like

Can’t answer for Rick, but I suppose he’s doing that because he’s using the velocity to turn the sprite around instead of the scale, and the speed won’t necessarily return the expected value, if the Rigidbody’s speed is 20 your enemy will be huge when it turns, this way the enemy can stay the same size all the time. There’s an issue with this approach, if the scale of the enemy is other than 1, your enemy will change sizes, which you might not want.

Your approach is perfectly fine and it solves Rick’s method issue, but at the same time it also has some other issues like the sprite not turning where it should in specific situations, Rick’s method doesn’t have this issue, so choose whichever you want, just be aware of this issues, or maybe use a combination of both methods to prevent any of this bugs from happening.

1 Like

Privacy & Terms