How to rotate mesh by aligning normal with axis?

I have a mesh that has been arbitrarily rotated. I would like to rotate it so that it is flat on the ground. My idea is to find the closest normal to the y-axis and then align that normal to the axis. I’m using a widely accepted answer on Stackoverflow as a basis: math - Finding quaternion representing the rotation from one vector to another - Stack Overflow

However, I am getting a weird skewed result instead of the rotation that I would expect. After the rotation, I would expect the normal of the blue face to be (0, 1, 0) (aligned to the y-axis). If you comment out line 50, you can see what the box looks like before applying the quaternion.

Does anyone have experience with this? I’m afraid there is likely just something I don’t understand about quaternion rotations happening here.

Small update: normalizing the resulting quaternion fixes the weird skewing I was seeing, but still does not align the mesh like I’d expect.

This may be of use

Thanks! That did get me on the right track to conceptually understand what was happening. It turns out, I was also using the wrong method to do the actual quaternion rotation.

Solved here :slight_smile:

I’ve made an alternate implementation using the method @JohnK referenced. I found the ‘normal’ you used odd, since it isn’t normal to Y - perhaps it’s just in the plane of the normal you want. I find the RotationFromAxis method easier to understand and use in my code, but that’s maybe just me.

2 Likes

Thanks so much for the alternate implementation! I marked yours as solution because I do like the RotationFromAxis method a bit more. Thanks for the suggestion