Reputation: 113
I have an object that I want to rotate smoothly on its Y axis several times, the RotateCount (number of times the object rotate on itself) is a variable, so I can change it to the number I want. I wrote the code below below but the object rotate only once? how can I fix that please?
public IEnumerator RotateObject()
{
yield return new WaitForSeconds(0.9f);
RotateCount = 5;
float Yrot = 360f;
float t = 0;
float targetRot = 0;
Vector3 eulers = object.transform.rotation.eulerAngles;
while (targetRot < Yrot)
{
t += Time.deltaTime;
targetRot = Mathf.Lerp(targetRot, Yrot * RotateCount, t * (0.3f * RotateCount));
object.transform.rotation = Quaternion.Euler(eulers.x, targetRot, eulers.z);
yield return null;
}
object.transform.rotation = Quaternion.Euler(eulers.x, Yrot, eulers.z);
}
Upvotes: 3
Views: 67
Reputation: 4037
It rotates only once, because your Yrot
variable is set to 360f
which causes the Coroutine to stop after one turn. Instead of multiplying it in the line where you set the targetRot
variable in your while
loop, you may want to use it as an exit condition and maybe either multiply it in the while
loop head with Yrot
or do that above, so you only need to do it once, like so:
public IEnumerator RotateObject()
{
yield return new WaitForSeconds(0.9f);
RotateCount = 5;
float Yrot = 360f * RotateCount;
float t = 0;
float targetRot = 0;
Vector3 eulers = object.transform.rotation.eulerAngles;
while (targetRot < Yrot)
{
t += Time.deltaTime;
targetRot = Mathf.Lerp(targetRot, Yrot, t * (0.3f * RotateCount));
object.transform.rotation = Quaternion.Euler(eulers.x, targetRot, eulers.z);
yield return null;
}
object.transform.rotation = Quaternion.Euler(eulers.x, Yrot, eulers.z);
}
Upvotes: 1