Unity Convert LocalSpace to WorldSpace


Sat Jan 23 2021 13:06:59 GMT+0000 (UTC)

Saved by @cotterdev #c#

//You need this because ur velocity is in localSpace
//This works if you start the game at 0,0,0 rotation,
//what if you start the game at 0,180,0 rotation?  
//Then your up arrow will move you backwards.

//Get inputs
float horzInput = Input.GetAxis("Horizontal");
float vertInput = Input.GetAxis("Vertical");

//Calc Velocity
Vector3 direction = new Vector3(horzInput, 0.0f, vertInput);
Vector3 velocity = direction * _speed;

velocity.y -= _gravity;

//Convert localSpace velocity to worldSpace
velocity = transform.transform.TransformDirection(velocity); //<-Weimberger's way
velocity = transform.TransformDirection(velocity); //<-myWay

_controller.Move(velocity * Time.deltaTime);