Movement Script Results In Character Spinning Around

Hello,

I have a movement script attached to my character and I now want to make it so the character will face the direction that he is moving in (when the user presses the left arrow, the character faces and moves towards the left, and when they press the right arrow, the character faces and moves towards the right). However, when I do this, my character moves correctly but he keeps spinning. Here is my script:

 horizontalMovement = Input.GetAxisRaw("Horizontal") * speed;
 transform.position += new Vector3(horizontalMovement, 0, 0) * Time.deltaTime;
      

  if (Mathf.Abs(horizontalMovement) == speed)
        {
            Vector3 newLocalScale = transform.localScale;
            newLocalScale.x *= -1;
            transform.localScale = newLocalScale;
        }

Can anyone help me with this? Thank you so much!

transform.Rotate(0, speed, 0)
should allow for rotation in the direction of the speed

Hello!
I’m guessing this is in an Update function and will therefore get executed every frame. So each frame in which you’re moving we’ll enter that if-statement and multiply our scale by -1. So while we’re moving then the scale will be adjusted like this:

Frame 1: scale = 1;

Frame 2: scale = 1 x -1 = -1;

Frame 3: scale = -1 x -1 = 1;

Frame 4: scale = 1 x -1 = -1;

Can you see how this would flip back and forth?

I’d suggest a solution would be to just define which direction is 1 and which is -1, say for example right is 1 then your code could be:

horizontalMovement = Input.GetAxisRaw("Horizontal") * speed;
transform.position += new Vector3(horizontalMovement, 0, 0) * Time.deltaTime;
       
 if (Mathf.Abs(horizontalMovement) == speed)
{
    Vector3 newLocalScale = transform.localScale;

    if (horizontalMovement > 0 && newLocalScale.x < 0
            || horizontalMovement < 0 && newLocalScale.x > 0)
    {
        // this check could also use the XOR operator: "horizontalMovement > 0 ^ newLocalScale.x > 0"
        newLocalScale.x *= -1;
    }

    transform.localScale = newLocalScale;
}