CharacterController.Move and gameObject.transform.forward

Hello!

I have a beginner question for you. I’m working on my first game for a school project and I found this in the Unity Documentation about CharacterController.Move. I used the code in my project and it worked; although, I made some adjustments to the playerSpeed, jumpHeight, and gravityValue variables to suit my game.

While I was going through the code, so I could understand what was happening more fully, I became puzzled by the code:

Vector3 move = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
        controller.Move(move * Time.deltaTime * playerSpeed);

        if (move != Vector3.zero)
        {
            gameObject.transform.forward = move;
        }

What is the purpose of the if statement here? From what I think I understand, the movement has already been handled by the “controller.Move(move * Time.deltaTime * playerSpeed);” I even commented the if statement out and checked in game after resetting the attached script on my player object and I was still able to move as before.

I find it really bothersome to not understand what a piece of code is doing, so I would greatly appreciate it if someone could help enlighten me to why this if statement is included here.

gameObject.transform.forward is essentially the direction your gameObject is facing. So setting it to your ‘move’ value is essentially rotating your gameObject to face in the direction it just moved.

If your user isn’t providing any input (ie both the horizontal and vertical axis are zero) then the if statement will prevent you from assigning (0,0,0) as the direction your gameObject is facing (which I guess might lead to odd results).

Okay. I think I understand that. Thank you for the explanation!