Rotate Rigidbody on Y Axis based on Velocity on X and Z axis

I have a Rigidbody (cube) that I am moving on the X and Z axis by adding force to it.

I’d like to have its “face” rotate toward the velocity (on the Y axis) so that it is facing the direction it is moving.

I am sure this is simple enough, but after googling for over an hour and trying out some different solutions I can’t seem to get it to work.

I know the code to rotate is simple enough:

rb.rotation = Quaternion.Euler(0, heading, 0);

But calculating “heading” is my issue. I can do it with a bunch of conditionals and make heading equal the some hard set rotations … but there has to be a better way.

Thanks in advance.

Calculate the average (i think) of the x and y velocities of the rigidbody that is moving
( heading = (yourRigidBody.velocity.x + yourRigidBody.velocity.y)/2 )

That, I believe, is how you calculate the heading variable. Let me know what happens. (Word of advice, as I have learnt in the past, this won’t end well if you player has a constant velocity and you don’t compensate for it in the median value calculation. Ie: an infinite runner)

Basing it off of Velocity proved to be a bit … awkward, just based it off of general direction instead. But, it gets the goal accomplished:

using UnityEngine;
using System.Collections;

public class Physics_PlayerController : MonoBehaviour
{
    public float speed;
    private Rigidbody rb;

    void Start()
    {
        speed = 15;
        rb = GetComponent<Rigidbody>();
    }

    void FixedUpdate()
    {
        rb.WakeUp();
        float moveHorizontal = Input.GetAxis("Horizontal");
        float moveVertical = Input.GetAxis("Vertical");
        
        Vector3 movement = new Vector3(moveHorizontal, 0.0f, moveVertical);
        rb.AddForce(movement * speed);
        float heading = Mathf.Atan2(moveHorizontal, moveVertical) * Mathf.Rad2Deg;
        
        if (moveHorizontal != 0 || moveVertical != 0)
        {
            rb.rotation = Quaternion.Euler(0, heading, 0);
         
        }
    }
}

@hyubusa? rigidbody.moverotation ?