# Rotate in set amount of time.

Discussion in 'Scripting' started by SupaPuerco, May 30, 2008.

1. ### SupaPuerco

Joined:
Aug 17, 2005
Posts:
48
I am trying to interpolate the rotations/positions of two objects in a fixed amount of time using a coroutine. I've got the solution for position which is :

Code (csharp):
1. function CameraMoveAnimation() {
2.     var dist : float = Vector3.Distance(cameraOrigin, cameraDestination);
3.     var rate : float = dist / cameraAnimationSpeed;
4.     for (i = 0.0; i < 1.0; i +=  rate / dist * Time.deltaTime ) {
5.         theCamera.transform.position = Vector3.Lerp(cameraOrigin, cameraDestination, i);
6.         yield;
7.     }
8. }
9.
How do I do the same for rotation?

2. ### SupaPuerco

Joined:
Aug 17, 2005
Posts:
48

Code (csharp):
1. function CameraMoveAnimation() {
2.     var dist : float = Vector3.Distance(cameraOrigin, cameraDestination);
3.     var rate : float = dist / cameraAnimationSpeed;
4.     for (i = 0.0; i < 1.0; i +=  rate / dist * Time.deltaTime ) {
5.         theCamera.transform.rotation = Quaternion.Lerp(cameraOriginRotation, cameraDestinationRotation, i);
6.         theCamera.transform.position = Vector3.Lerp(cameraOrigin, cameraDestination, i);
7.         yield;
8.     }
9.
10. }
11.

### Volunteer ModeratorModerator

Joined:
Jul 19, 2006
Posts:
32,318
Edit: beat me to it. Pretty much the same thing, except you'd use Quaternion.Angle instead of Vector3.Distance and Quaternion.Slerp instead of Vector3.Lerp. (Or Quaternion.Lerp, but as the docs say, it looks worse if the angles are far apart.) Also probably worth using local variables so you can make the coroutine generic, and able to be applied to any object.

Code (csharp):
1. var object1 : Transform;
2. var object2 : Transform;
3. var rotationSpeed : float = 2;
4.
5. function Start () {
6.     RotateBetweenAngles (gameObject.transform, object1.rotation, object2.rotation, rotationSpeed);
7. }
8.
9. function RotateBetweenAngles (myTransform : Transform, myOrigin : Quaternion, myDestination : Quaternion, mySpeed : float) {
10.    var dist : float = Quaternion.Angle(myOrigin, myDestination);
11.    var rate : float = dist / mySpeed;
12.    for (i = 0.0; i < 1.0; i +=  rate / dist * Time.deltaTime ) {
13.       myTransform.rotation = Quaternion.Slerp(myOrigin, myDestination, i);
14.       yield;
15.    }
16. }
--Eric unityunity