How can I convert LOCAL transform.forward to WORLD Vector3?

Hi guys,

I’m using:

transform.Rotate(new Vector3(0, Input.GetAxis("Horizontal") * rotateSpeed * Time.deltaTime, 0.0f));
        
if(Input.GetKey(KeyCode.W)){
      transform.position += transform.forward * speed * Time.deltaTime;
}
if(Input.GetKey(KeyCode.S)){
      transform.position -= transform.forward * speed * Time.deltaTime;
}

because I need the player to move relative to the direction they face. For instance if the player is facing North and presses ‘W’ (up), they move north. If the player is facing East and presses ‘W’ (up) they move East.

But I also need this to work with the CharacterController, so need to convert to a Vector 3 (‘moveDirection’).

characterController.Move(moveDirection * Time.deltaTime);

Thoughts?

What you need to be doing is rotating the player and then forward will always be forward.

As indicated by DCordoba, transform.forward is already a vector defined in the World space.

What you really need is the vector expressed in the local space. In your case:

Vector3 moveDirection;
if(Input.GetKey(KeyCode.W)){
       moveDirection = Vector3.forward;
 }
 if(Input.GetKey(KeyCode.S)){
       moveDirection = -Vector3.forward;
 }
characterController.Move(moveDirection * speed * Time.deltaTime);