Search Unity

Rotating on Z axis with Slerp in a coroutine

Discussion in 'Scripting' started by winterfive, Nov 16, 2018.

  1. winterfive

    winterfive

    Joined:
    May 21, 2018
    Posts:
    31
    Hi all,

    I've been trying to rotate a flattened cube on its Z axis. Here's the code:

    Code (CSharp):
    1. private IEnumerator RotateCube()
    2. {
    3.     float time = 0f;
    4.     Quaternion start = _this.transform.localRotation;
    5.     Quaternion target = Quaternion.Euler(new Vector3(0f, _defaultY, _targetRotationZ));
    6.  
    7.     while (time < _rotationDuration)
    8.     {
    9.         _this.transform.rotation = Quaternion.Slerp(start, target, time / _rotationDuration);
    10.         yield return null;
    11.         time += Time.deltaTime;
    12.     }
    13.  
    14.     _this.transform.rotation = target;
    15. }
    _defaultY is assigned in Awake()
    _targetRotationZ is assigned earlier in the class (it 0 or -45 depending on when it's called).

    The square should rotate smoothly from 0 to -45 on Z only.
    The square starts with a rotation of 0, 21, 0.
    When I click on it, the square rotates to 0, 0, -45. It should be at 0, 21, -45.
    During the rotation, the x value goes up to a random value and then back to 0.
    When I click again, it rotates to 0, 0, 0 instead of its original rotation of 0, 21, 0.

    I've googled, debugged, and tried a few approaches with no luck.
     
    Last edited: Nov 19, 2018
unityunity