- Home /
Proper way to rotate an object?
I want my 2d object to rotate clockwise along the z-axis and then stop when it reaches -45 degrees. This is my current code
void FixedUpdate()
{
transform.Rotate(transform.forward * -1, speed * Time.fixedDeltaTime);
if (transform.eulerAngles.z - 360 <= -45)
speed = 0;
}
It does exactly what I want it to, but it doesn't seem very elegant. I don't like the fact that I have to constantly check in fixedupdate whether or not it's reached the desired angle and then manually stop it by setting the speed to zero. It just seems kind of awkward. Is there a better way to do this? Maybe a built-in function with one line of code? I don't want to use lerp because I'm afraid the rotation speed may slow down as it gets closer to the desired angle.
Answer by ahstein · Jun 26, 2018 at 11:22 PM
Quaternion.RotateTowards is similar to Lerp but it has a fixed step size. That seems like what you're looking for.
https://docs.unity3d.com/ScriptReference/Quaternion.RotateTowards.html
Thank you. Got it working with just two lines of code
Quaternion angle = Quaternion.Euler(0f, 0f, -45f);
transform.rotation = Quaternion.RotateTowards(transform.rotation, angle, speed * Time.fixedDeltaTime);