0

I have an object that I want to loop when I press the U key using Quaternion:

 public KeyCode UTurn;

    void UNotation()
    {
        if (Input.GetKeyDown(UTurn)) {

            Quaternion rotation2 = Quaternion.Euler(new Vector3(0, 90, 0));
            StartCoroutine (rotateObject(objectToRotate, rotation2, 1f));
            // Debug.Log("Turn: U");
        }
    }

Then, I have my IEnumerator function that allows my object to rotate in 2 seconds, like this:

 bool rotating = false;
    public GameObject objectToRotate;

    IEnumerator rotateObject(GameObject gameObjectToMove, Quaternion newRot, float duration)
    {
        Debug.Log("Accessed IEnumerator function...");
        if (rotating)
        {
            yield break;
        }

        rotating = true;


        Quaternion currentRot = gameObjectToMove.transform.rotation;

        float counter = 0;
        while (counter < duration)
        {
            counter += Time.deltaTime;

            Debug.Log("Rotated!");

            gameObjectToMove.transform.rotation = Quaternion.Lerp(currentRot, newRot, counter / duration);

            yield return null;

        }

        rotating = false;
    }

I then call the UNotation() function in the Update() function:

 void Update () {
        UNotation();
    }

I want to be able to continue rotating the cube again and again pressing the U key once each rotation has finished, but for some reason I can only get the object to rotate once and then it doesn't rotate anymore, however the two Debug.Log calls in the IEnumerator function gets checked to console just fine, so for some reason this line stops working:

gameObjectToMove.transform.rotation = Quaternion.Lerp(currentRot, newRot, counter / duration);

I've tried making a loop inside the function but it ended up crashing my game. Appreciate any help!

toadflax
  • 375
  • 4
  • 17
  • Does this have to be a co-routine? It sounds like something you should track in the component (is making a u-turn) and track that for 2 seconds over the normal game loop. – ps2goat Feb 26 '18 at 23:38
  • The current code you are using is just rotate the object to that provided rotation. The first time you run it, you get the `(0, 90, 0)` angle rotation. The second time you run it, you won't see it because it is already at that angle. You got the function from the duplicate. Look at the section that says **INCREMENTAL ANGULAR ROTATION OVER TIME**. That's what you are looking for. It will rotate by incrementing the rotation with the rotation you provided. – Programmer Feb 26 '18 at 23:43

0 Answers0