Rotate to orient to sphere surface, but maintain local Y axis

Hi, I’m trying to implement functionality for a character running around the surface of a sphere (think Mario galaxy), and I’m trying to get them to orient correctly to the sphere surface. I’ve been able to get it to rotate correctly to the sphere surface with the below code, but the problem is that it always modifies my y rotation as well.

Vector3 gravityDirection = sphere.transform.position - transform.position;
gravityDirection.Normalize();
		
transform.rotation = Quaternion.FromToRotation (Vector3.up, -gravityDirection);

I’ve tried a few different combinations of converting the quaternion to Euler angles, setting the y rotation to the players current Euler y rotation, and then setting the rotation to that, but it doesn’t seem to work. The character starts to glitch out rotating every direction super fast.

Any thoughts on how I might be able to achieve this correctly?

Do it like this.

// In this case, the normal is more useful!
Vector3 groundNormal = transform.position - sphere.transform.position;
// Here we work out what direction should be pointing forwards.
Vector3 forwardsVector = -Vector3.Cross(groundNormal, transform.right);
// Finally, compose the two directions back into a single rotation.
transform.rotation = Quaternion.LookRotation(forwardsVector, groundNormal);