Move rigidbody in relation to active camera

Hi,

I am using a kinematic rigidbody as my character and moving it across a plane using the following code:

    void FixedUpdate() {

    float xPos = Input.GetAxis("Horizontal") * _player.playerSpeed * Time.deltaTime;
    float yPos = Input.GetAxis("Vertical") * _player.playerSpeed * Time.deltaTime;

    Vector3 newPos = new Vector3(xPos, 0, yPos);
    _position = _position + newPos;

    _direction = new Vector3(xPos, 0, yPos);
    _direction = _direction.normalized;

    if(_direction.sqrMagnitude > 0.01)
        _player.transform.rotation = Quaternion.Slerp (_player.transform.rotation, Quaternion.LookRotation (_direction), Time.deltaTime * 10);

    //if(_position != Vector3.zero)
    //{
    _player.rigidbody.MovePosition(_position);
    //}
}

It's working fine, but as the camera moves, the axis get mixed up and the control start to get inverted. I guess this is because as the camera moves, the axis directions change but Unity has no way of knowing that... Is there some kind of modification I can make to my code so that the input is relative to the Camera location?

Any help would be greatly appreciated!

You have to make the direction of movement relative to the camera. To fix this, add:

newPos = Camera.main.transform.TransformDirection(newPos);

after:

Vector3 newPos = new Vector3(xPos, 0, yPos);

That will put newPos in the camera's local space so when your add it to position, it will be relative to the camera.


Then your will also have to fix the rotation. To do that add:

_direction = Camera.main.transform.TransformDirection(_direction);

after:

_direction = new Vector3(xPos, 0, yPos);