Rotate an object a set angle over time? (C#)


I have an object that I want to rotate 20 degrees, but I want it to rotate ONLY 20 degrees over a few seconds. I just cannot get it to work!

I’ve tried things like:

object.transform.Rotate(Vector3.right * (20 * Time.deltaTime));

But from what I understand, this just rotates it by 20 degrees every second and doesn’t stop at 20. I tried using an “if (object.transform.rotation <=20)” with the above code but that didn’t stop it either.

I have my object moving forwards in the z-axis with Lerp by using:

object.transform.position = new Vector3(object.transform.position.x, object.transform.position.y, Mathf.Lerp(object.transform.position.z, (destination.transform.position.z+10), Time.deltaTime));

That seems to work fine when moving an object a certain distance, but I tried to implement the same idea with rotation and I just can’t do it. I get quite a lot of errors about Quaternions and Vectors can’t be converted etc.

I don’t fully understand Quaternions but I have a feeling I have to use them.

Any help would be much appreciated!
Thanks alot!

To rephrase the question, I don’t have to be able to set how many seconds it takes to rotate. I just want it to gradually rotate, but stop after a certain amount of degrees.

Everything I try seems to just make it continuously rotate, but I just want it to stop rotating after a set amount of degrees.

The answer is to use a coroutine or a condition in your Update to uses a state to decide whether you should be rotating or not.

Coroutines are easy for this:

     IEnumerator RotateMe(Vector3 byAngles, float inTime) {
          var fromAngle = transform.rotation;
          var toAngle = Quaternion.Euler(transform.eulerAngles + byAngles);
          for(var t = 0f; t < 1; t += Time.deltaTime/inTime) {
               transform.rotation = Quaternion.Lerp(fromAngle, toAngle, t);
               yield return null;

Then to rotate by 20 degrees in 5 seconds - do this once when you want it to start

    StartCoroutine(RotateMe(Vector3.right * 20, 5));