Could someone explain this code for me please?

So I’m following burgzergarcade’s hack and slash rpg tutorial, and for moving the character we used this code:

(These are the variables)

public CharacterController controller; //This is assigned to the controller elsewhere in the script
private Vector3 moveDirection = Vector3.zero;
private CollisionFlags collisionFlags;

Here is the code which gets it to move

		if (controller.isGrounded) {
			moveDirection = new Vector3 (0, 0, Input.GetAxis("Vertical"));	
			moveDirection = transform.TransformDirection(moveDirection).normalized;
			moveDirection *= moveSpeed * Time.deltaTime;
		}
		
		collisionFlags = controller.Move(moveDirection);
	}

I didn’t really understand the brief description given in the tutorial, and I looked up all the functions (collisionFlags and TransformDirection)in the unity script Reference but I still don’t really understand how this works. (I understand IsGrounded and Normalized, just not the rest) The code works, but I just don’t understand why it works.
Prior to the tutorial I just used this to go forward, and the opposite to move backwards:

if (Input.GetAxis("Vertical") > 0) {
    controller.Move(transform.forward * moveSpeed * Time.deltatime);
}

The results seem to be the same, So would someone be able to explain how this (new) code gets my character to move, and the difference between it and my old code?

In order to understand this code, you first have to understand the different between local and world coordinates. Local coordinates are relative to the object. The origin of those coordinates are at the pivot point of the object. Relative to that coordinates system, ‘forward’, ‘back,’ ‘up,’ ‘down,’ ‘left,’ ‘right’ always remain constant. For example, the local ‘forward’ is always (0,0,1) which is also Vector3.forward. ‘Up’ is always (0,1,0) which is also Vector3.up. It doesn’t matter what way the object is facing since the coordinates are always relative the object.

World coordinates are based world axes. We can get our ‘forward’ vector in world space from the transform using Transform.forward. Likewise ‘up’ is Transform.up, and ‘right’ is Transform.right. To can translate from local to world using Transform.TransformDirection(). So these two things are equivalent:

transform.forward == Transform.TransformDirection(Vector3.forward)

So the new code you don’t understand constructs a vector forward in the local coordinated system. Then it translates it to the global coordinate system. For what you are doing here, I cannot any benefit to the new code, and the old code is simpler. The new code might be simpler if you were combining forward/back with left/right movement:

moveDirection = new Vector3 (Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));