I'm making a 2D platformer with Unity. A few days ago, I was testing the game; the player could face right and left based on its moving direction and animations were playing correctly. I exited playmode because I had to assign the player position into a slot in inspector for the checkpoints. After assigning that, I entered the playmode again and surprisingly, I encountered a strange problem. The animations were working but the player was not able to face left when it was moving to the left side. I still have this problem. This is very strange to me because I didn't change anything neither from the code nor the inspector. So I believe this is a random Unity bug. After testing the game many times, I found out these:
- If I disable Animator component, the player can flip again but obviously the animations won't play.
- I can have both Animator and flipping working at the same time only when I check or uncheck root motion in playmode. But when I exit, the problem returns. So the previous unchecked or checked root motion will not work in the next playtest, so I can just check or uncheck it while the game is playing; otherwise it won't work.
These are the reasons why I think the Animator component prevents the player from flipping but I have no idea why this is happening because this component has nothing to do with the facing code. Thanks in advance.
This is the code I use for flipping the protagonist:
bool isFacingLeft;
void Update()
{
//Move the player.
//Target velocity is defined in another script and is not important in this context.
targetVelocity = new Vector2(Input.GetAxis("Horizontal") * maxSpeed, 0);
//Flip the player's localScale.x if the move speed is greater than .01 or less than -.01.
if (isFacingLeft == true)
{
transform.localScale = new Vector2(Mathf.Abs(transform.localScale.x) * -1, transform.localScale.y);
}
else
{
transform.localScale = new Vector2(Mathf.Abs(transform.localScale.x), transform.localScale.y);
}
if (targetVelocity != Vector2.zero)
isFacingLeft = targetVelocity.x < 0 ? true : false;
}