Why is Terrain Sample height resetting player rotation

When I rotate the player on input with MoveRotation no issues however when I try to sample the terrain height to adjust the transform then the player character only moves forward on the terrain since the rotation gets reset to ZERO.`

        void Rotating(float horizontal, float vertical, float slerpDampTime)
        {
     
                Quaternion camRotation = mainCam.transform.rotation;
                camRotation.x = 0;
                camRotation.z = 0;
                // we need some axis derived from camera but aligned with floor plane
     
                Vector3 forward = mainCam.transform.TransformDirection(Vector3.forward);//forward of camera to forward of world
                //local forward vector of camera will become world vector position that is passed to the forward vector of the player (target) rigidbody
                //(The cam and player(target) vector will now always point in the same direction)
     
                forward.y = 0f;
                forward = forward.normalized;
                Vector3 right = new Vector3(forward.z, 0.0f, -forward.x);
                Vector3 targetDirection = (horizontal * right + vertical * forward);
                if (targetDirection.sqrMagnitude > 1f)
                {
                    targetDirection = targetDirection.normalized;
                }
                Quaternion targetRotation = Quaternion.LookRotation(targetDirection, Vector3.up);
                Quaternion newRotation = Quaternion.Lerp(GetComponent<Rigidbody>().rotation, targetRotation, slerpDampTime * Time.deltaTime);
     
                GetComponent<Rigidbody>().MoveRotation(newRotation);
     
        }
     
     
     
        void LateUpdate()
        {
            if (Terrain.activeTerrain != null)
            {
                var newpos = transform.position;
                newpos.y = Terrain.activeTerrain.SampleHeight(transform.position);
                transform.position = newpos;
            }
     
        }
     
     
     
     
    }

I’d suggest that perhaps you code a new Terrain variable and copy the terrain data over at the start. If the heightmap is not going to change at all then you can sample the copy.

~

Or instead of using SampleHeight with the Terrain use

GetHeight(x, y) on the TerrainData.