Rotate object to face direction of movement

Hi, I have a rigidbody which I am moving around in a 2D way 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;

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

}

It's working fine, but I'm struggling to make it so the gameObject rotates to face the direction in which the object is moving. Most of the code I have found assumes we are wanting to move X, Y and Z where as I am only really interested in X and Z.

If anyone has anyone suggests as to how I can get this functionality I'd be very grateful :)

You can simply set the object’s blue axis to the rigidbody’s velocity Vector3:

transform.up = rigidbody.velocity;

If you want to use a rigbody…

Could you use Transform.LookAt, and then just lock the Y-axis to whatever you need it to be?

Sorry I can't provide a code sample, I'm still in the "trial-and-error the syntax as I go" stage of Unity-specific javascript, but the theory is basically take the direction you're moving, either pulled from the .x and .z of your velocity or tracked frame to frame as a difference of previously-saved and current x & z position and drop it in a vector. I believe Unity has some LookAt or set-rotation-to-face-vector functions built in, otherwise you're back to using a Mathf.atan2 call and euler rotations.

But Spike's probably got the straightforward built-in: .LookAt where you're going, and then set the pitch component of the object rotation to 0.

See the top voted answer in this thread