1

I'm trying to make a teeter totter like object rotate with Unity and for some reason the rotation is instant, rather than a gradual movement. I had looked into Slerp and Lerp previously and am unable to get it to work with either. I was wondering if anyone had any insight as I'm sure i'm missing something stupid and easy xD. Thank you! Here is the method.

private void Rotate(float rotateAmount)
    {
        var oldRotation = transform.rotation;
        transform.Rotate(0, 0, rotateAmount);
        var newRotation = transform.rotation;
 
        for (float t = 0; t <= 1.0; t += Time.deltaTime)
        {
            transform.rotation = Quaternion.Slerp(oldRotation, newRotation, t);
        }
        transform.rotation = newRotation;
    }
}
Holden
  • 109
  • 1
  • 9

1 Answers1

6

All the rotation done in the for loop are happening under one frame. You can't see them changing under one frame. Make the Rotate function to be a coroutine function then wait for a frame in each loop with yield return null and you should see the changes over time.

private IEnumerator Rotate(float rotateAmount)
{
    var oldRotation = transform.rotation;
    transform.Rotate(0, 0, rotateAmount);
    var newRotation = transform.rotation;

    for (float t = 0; t <= 1.0; t += Time.deltaTime)
    {
        transform.rotation = Quaternion.Slerp(oldRotation, newRotation, t);
        yield return null;
    }
    transform.rotation = newRotation;
}

Since it's a coroutine function, you start it instead of calling it directly:

StartCoroutine(Rotate(90f));

I noticed you used transform.Rotate(0, 0, rotateAmount) to get the destination angle. You don't need to do that. If you need to rotate object to another angle from the current angle, get the current angle then add it to the destination angle and use Vector3.Lerp to lerp the rotation.

See the "INCREMENTAL ANGULAR ROTATION OVER TIME:" section from this post.

Programmer
  • 121,791
  • 22
  • 236
  • 328