I’ve got a coroutine that I’m calling to rotate and object so that it faces another direction using Quaternion.Slerp. It doesn’t seem to be rotating correctly however:
public IEnumerator QuatRotate(float _rotateSpeed)
{
float rate = 1.0F / _rotateSpeed;
float timeScale = 0.0F;
while(timeScale < 1.0F)
{
timeScale += Time.deltaTime * rate;
transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.Euler(0F,180F,0F), timeScale);
print(timeScale);
yield return null;
}
}
I’m printing out timeScale to the console and I can see that it’s incrementing upwards to a value of 1.0F as it should, but the slerp function seems to be ignoring this and rotating at a different rate, even though I set timeScale as its t
parameter. I get how Unity’s Lerp functions work, using 0…1 as relative distance between the first two parameters, but it doesn’t make sense when I see timeScale incrementing linearly while the object rotates either too fast or too slow.
Below is your code with a few tweaks. From your naming I assumed you would want _rotateSpeed to represent the number of times the object would make the 180 degree rotation in a second (though it only makes one rotation). So a value of 2 will rotate the 180 degrees in 1/2 second. A value of 0.1 will take 10 seconds to rotate. Using the current rotation rather than saving the start rotation was the biggest issue with the timing.
public IEnumerator QuatRotate(float _rotateSpeed)
{
float rate = 1.0F / _rotateSpeed;
float timeScale = 0.0F;
Quaternion q = transform.rotation;
while(timeScale < rate)
{
timeScale += Time.deltaTime;
transform.rotation = Quaternion.Slerp(q, Quaternion.Euler(0F,180F,0F), timeScale/rate);
//print(timeScale);
yield return new WaitForEndOfFrame();
}
}
This is how I rotated my camera to rotate to a specified location. You could use it or modify it to your needs. It is in boo.
def rotateToObject ( target as Transform, time as single ) as IEnumerator:
initialRotation as Quaternion = transform.rotation
targetRotation as Quaternion = Quaternion.LookRotation(target.position - transform.position)
rate as single = 1.0/time
delta as single = 0.0
while delta < 1.0:
delta += rate * Time.deltaTime
transform.rotation = Quaternion.Slerp(initialRotation, targetRotation, delta)
yield
Using ‘as’ is Boo’s way to instantiating type. Also single is float in C# and JS