Hi, I want to turn an object smoothly and continuously around the Y axis, So I have this code:
public class TempScript2 : MonoBehaviour
{
private float YAW_Rotation;
void FixedUpdate ()
{
YAW_Rotation +=3;
var startRotation = transform.rotation;
var endRotation = Quaternion.Euler(0, YAW_Rotation, 0);
transform.rotation = Quaternion.Lerp(startRotation, endRotation, Time.fixedDeltaTime);
}
}
This work great, however when I change the value of the increment to 4 (YAW_Rotation +=4),
the object will rotate at some amount and then suddenly will start to rotate in the opposite direction at certain amounts.
any one can explain to me why this is happening ? I know that I should pass fixed values to the Lerp function to do a “real lerp”, however I don’t need the object to reach its destination, I want it to rotate while the user is pressing the arrows (YAW_Rotation +=3 * YAW_Input) (this is a helicpoter controller)…
The reason you’re limited in this way is due to the nature of Euler Angles. By nature, there are an infinite number of ways to define any angle using Euler rotations. For example, a 180-degree rotation on the Y-axis is identical to a rotation of 180 degrees on both the X- and Z-axis with no Y-axis rotation.
This case is based on a different principle, however. Euler rotations are 0-360 degrees (exclusive). In other words, you never reach a 360-degree rotation, but instead reset to 0 degrees again. Because of this, you reach the point where your endRotation variable thinks it’s a very low number and you quickly rotate the other direction until that value is greater than your starting rotation again.
You may want to try something like this instead:
public class TempScript2 : MonoBehaviour
{
private float YAW_Rotation;
void FixedUpdate()
{
Quaternion startRotation = transform.rotation;
Quaternion endRotation = Quaternion.AngleAxis(YAW_Rotation, Vector3(0, 1, 0));
// Option 1: Based on your previous script
transform.rotation = Quaternion.Lerp(startRotation, startRotation * endRotation, Time.fixedDeltaTime);
// Option 2: another means of handling the rotation
//var endRotation = Quaternion.AngleAxis(YAW_Rotation * Time.fixedDeltaTime, Vector3(0, 1, 0));
//transform.rotation *= endRotation;
}
}
That said, there are plenty of ways of approaching this beyond the two examples I gave, but AngleAxis calculates a rotation of any number of degrees as a Quaternion rotation function without factoring in Euler values’ modulo operations (%).
An added note, the Vector3(0, 1, 0) can be replaced with Vector3.up. More importantly, it’s simply the direction around which the rotation is applied. By association, if the rotation value is negative or the axis flipped upside down (-Vector3.up), the object would rotate the other direction instead.