- Home /
Why is Quaternion.FromToRotation() not working properly?
I'm trying to make a space game involving moving around on procedurally generated planets. I'm trying to get gravity working properly using a simple sphere to represent a planet, and a capsule to represent a player. I followed Sebastian Lague's "Faux Gravity" tutorial video, and implemented the code. The gravity part works just fine; the capsule falls in the direction of the planet. However, the capsule does NOT orient its rotation properly.
The function that is supposed to line up the capsule in the direction of gravity is as follows:
body.rotation = Quaternion.FromToRotation(bodyUp, gravityUp);
where body is the rigidbody reference to the capsule, bodyUp is the vector for the local upward direction of the capsule, and gravityUp is the normalized vector for the direction between the planet's center and the capsule.
The function as I understand it is supposed to orient the capsule so its up direction matches the gravity direction. Instead, when the capsule moves down from the top of the sphere, it leans upward (in world space, so on the planet surface sideways), to the point that it leans completely on its side at the bottom and movement (which is based around local space) becomes impossible.
Does anyone know why this is not working and/or have a solution?
Answer by unity_ek98vnTRplGj8Q · Aug 21, 2020 at 10:06 PM
Try
body.rotation *= Quaternion.FromToRotation(bodyUp, gravityUp);
instead. To explain - Quaternion.FromToRotation give the rotation to rotate one vector into another vector. So, in this case, the resulting quaternion will represent the rotation that will transform our objects up vector into the gravity normal vector. However we don't want to set this as the rotation, because now the relative rotation we just calculated will become our absolute orientation, which we definitely don't want. Instead, we want to add this rotation to our objects current orientation. To add a rotation to your current orientation, you can multiply the orientation by the desired rotation.
Answer by wrmungas · Aug 23, 2020 at 01:45 AM
Thank you guys both! I probably just missed a multiply sign from the video or something :)