Rotation based on surface? Use the normal or is there a better method?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Lamb

For my project, I’m trying to rotate the player (and some other objects) to align with the ground’s surface. This is in 3D. Say a box is dropped onto a sloped surface, you’d expect the box to rotate along the floor, so that the bottom of the box and the floor are parallel.

I figured the easiest way would be to get the normal of a surface, then rotate the player so their “Up” direction is the same as the normal. Got the normal easily with raycast, but using it is hard since rotation in Godot is more complicated than I expected.

I’ve grasped the concept of basis (I think) but I still can’t seem to figure out how to modify them so that the players X basis points along the “left/right” slope of the ground, and the Z basis points along the “forward/backward” slope of the ground.

But… I thought getting the new basis(es?) would be as simple as

Y basis = normal normalized
X basis = normal normalized, rotated +90 degrees across the Z axis
Z basis = normal normalized, rotated -90 degrees across the X axis

But that doesn’t work. It distorts the player instead of rotating them as I had hoped.

So… after that elongated explanation of what I’ve tried… my question is:

How can I rotate an object so it aligns with a sloped surface? Is using the normal the best way to do this? Or is there a better way?

Secondary questions:
Why doesn’t the method I tried work? Is my understanding on basis flawed?
Also what’s really so bad about euler angles?

Sorry for asking a question that’s actually multiple questions. Really only the main question requires an answer but the other stuff is curiosity

I’ve struggled a lot with this, but with this tutorial from KidsCanCode I managed to align my character with the ground normal. It’s from Godot 3, but I think it should work in Godot 4 as well.

KinematicBody: align with surface :: Godot 3 Recipes

I don’t understand the math behind it very well, so I can’t answer your other questions, but I hope this tutorial can help you with this problem.

umaruru | 2023-05-25 07:21

Wow thank you! I didn’t realize it’d be this simple.
Only flaw with this is if the floor’s surface is angled both ways (up/down & left/right) there’s some arbitrary rotation of the player (even happens in the videos lol). I can probably iron that out though.

Lamb | 2023-05-25 18:27