Cross-posted from Unity Questions, since I’ve gotten no replies there.
Hoping someone can explain the math behind this:
I am working on a survival game and needed to rotate walking animals to match the slope of the terrain under them without affecting the direction they were pointing. IE, they needed to rotate in the local Y axis, without affecting their local X and Z axes.
After a lot of searching and trouble I came across this code:
RaycastHit hit;
if(Physics.SphereCast(transform.position, 0.5f, -(transform.up), out hit, yourDistenceToGroundYouWant, yourGroundLayers))
{
transform.rotation = Quaternion.LookRotation(Vector3.Cross(transform.right, hit2.normal)
}
It’s on this thread, for some context: Rotating a player to match terrain slope - Questions & Answers - Unity Discussions
It was practically a 1 to 1 drop in to my own script, resulting in this:
RaycastHit hit;
if (Physics.Raycast(transform.position, -Vector3.up, out hit))
{
transform.rotation = Quaternion.Lerp(transform.rotation, Quaternion.LookRotation(Vector3.Cross(transform.right, hit.normal)), .01f);
}
Now, no complaints from me and I’m really grateful to @Fanttum for the answer, but what is bothering me is that I don’t know WHY this code does what it does. Quaternions are mystery oil to me; could someone spread some enlightenment here, so I’m not just another copy-paste-codemonkey in this regard?
Thanks!