So I am working on a gravity altering game that has forced me to better understand how angles work, although I am still struggling. In my game, I want to give the player the ability to flip gravity on demand. (Gravity is manually coded in, it is just a force being constantly applied to vector3.down). However, my issue isn’t with gravity, it is with accurately rotating the player 180 degrees. I also have to keep in mind that I plan on the player being able to walk on walls, meaning their rotation may not be strictly 0, 0, 0 or 0, 0, 180 (My current rotation function rotates the player along the Z axis). Basically, if the player was in a cube, the player could be standing on any surface within the cube. But not any slanted surfaces: all surfaces the player walks on are in iterations of 90 degrees. I have code currently to rotate the player, but it does not work accurately. Here is the code:
void Update()
{
if (Input.GetButtonDown("Flip"))
{
StartCoroutine(Rotate(rb.rotation * Quaternion.Euler(0, 0, 180)));
}
}
IEnumerator Rotate(Quaternion target)
{
yield return null;
while (Vector3.Angle(rb.rotation.eulerAngles.normalized, target.eulerAngles.normalized) != 0f)
{
rb.MoveRotation(Quaternion.Slerp(rb.rotation, target, .5f));
yield return null;
}
}
So when I call Rotate, I pass in the current rotation already rotated 180 degrees around the Z axis, I just have to get to that point. Then I use the IEnumerator to continue to rotate until the angle between the current rotation and our target rotation is zero (Supposedly). Each time it isn’t, use MoveRotation and Slerp to get closer, (this way the movement is more smooth). And it “almost” works. I suspect that Vector3.Angle is not totally accurate, because it always stops rotating barely before its target, with a few decimal points off. I tried adding normalized to the vectors being passed in, and I tried using Quaternion.Angle as well, but nothing seemed to fix the issue. I get the feeling that I should be approaching the problem in a completely different manner, but am not sure. Any help is much appreciated.