Player alignment with Terrain


I’ve recently been developing my own character player controller using a rigidbody and root-animations, it’s almost done but it’s missing one thing which I cannot seem to get working with smooth results.

Basically, I want the player to smoothly rotate to terrain slopes, like if it’s walking upwards.
I’ve tried using basic raycasts to the Terrain and used hit.normal, but it doesn’t seem to work when walking upwards.

Is there any simple solution to this, if so, can anyone provide the code for it as I’m completely out of ideas as to how I would go by solving this.

Ended up with this, which fits my use cases:

private void AlignRotation()
            Transform cTransform;
            if (!Physics.Raycast((cTransform = transform).position, Vector3.down, out var hit, float.PositiveInfinity,
                config.terrain, QueryTriggerInteraction.Ignore)) return;
            // Calculate the orientation to Terrain.
            var rotation = cTransform.rotation;
            var alignment = Quaternion.FromToRotation(transform.up, hit.normal) * rotation;
            var inverse = Quaternion.Inverse(rotation);
            var target = inverse * alignment;
            // Calculate the Delta Align Rotation.
            var delta = Quaternion.Lerp(Quaternion.identity, target, Time.deltaTime * 5);
            transform.rotation *= delta;