- Home /
 
The question is answered, right answer was accepted
[SOLVED] Why did the Rotation method stopped working after it became a coroutine?
I searched around the internet and found a neat solution to make an enemy rotate back and forth using some formulas... It was working beautifully when I was calling it at the update function.
But then I tried to put it inside a coroutine, and now the enemy doesn't go back and forth... in fact, it still rotates, but only on one direction.
I believe it's something with the way coroutines are called, but I cannot pinpoint exactly what the problem is... so if anyone could help, I would be really thankful!
The infamou method below:
 public void LookAround() {
         rotationTime = rotationTime + Time.deltaTime;
         float rotationAngle = Mathf.Cos(rotationTime / .5f);
 
         //now calculates rotationVelocity to be applied
         Vector3 rotationVelocity = (Vector3.up * rotationAngle * maxAngle) * rotationSpeed;
 
         //get object delta velocity
         Vector3 deltaVelocity = (rotationVelocity - rb.angularVelocity);
 
         //apply force
         rb.AddTorque(deltaVelocity, ForceMode.Impulse);
     }
 
               ` And as a Coroutine:
 public IEnumerator LookAround() {
             while (true) {
                 deltaTime = deltaTime + Time.deltaTime;
                 float phase = Mathf.Cos(deltaTime / .5f);
     
                 //now calculates rotationVelocity to be applied
                 Vector3 rotationVelocity = (Vector3.up * phase * maxAngle) * rotationSpeed;
     
                 //get object delta velocity
                 Vector3 deltaVelocity = (rotationVelocity - rb.angularVelocity);
     
                 //apply force
                 rb.AddTorque(deltaVelocity, ForceMode.Impulse);
     
                 Debug.Log(phase);
     
                 yield return null;
                 break;
             }
         }
 
              Why are you breaking the loop? This way it executes only once, so what's the point of it? Also how do you start the coroutine?
Answer by eidnog · Jan 05, 2019 at 03:01 AM
I just pasted the code above again and it worked! Oh snap