Search Unity

Using Quaternion.RotateTowards to rotate a specific direction

Discussion in 'Scripting' started by Zalstadt, Mar 19, 2019.

  1. Zalstadt

    Zalstadt

    Joined:
    Jul 2, 2018
    Posts:
    2
    I am working on a wheel that I have rotating through a list of items, at the end of that list I call
    Quaternion.RotateTowards(transform.rotation, Quaternion.Euler(0, 0, 0), 1.0f)
    in a while loop. Depending on the rotation of the wheel when this is called it rotates forward or backwards (fastest way to get to the target position). I was wondering if anyone knows a way of forcing a result of only spinning one direction every time even if it is the farthest rotation. Appreciate the help.
     
  2. Antistone

    Antistone

    Joined:
    Feb 22, 2014
    Posts:
    2,836
    I believe you can rotate one Quaternion by another Quaternion by mutliplying them together. So if you have a Quaternion that represents "one step" of rotation in the direction you want, you can mutliply by that in your loop instead of using RotateTowards. (Note: Quaternion multiplication is not commutative--be careful of the order!)

    You can also skip Quaternions entirely and directly rotate your object using Transform.Rotate() or Transform.RotateAround().
     
  3. wileyjerkins

    wileyjerkins

    Joined:
    Oct 13, 2017
    Posts:
    77
    You'd just use transform.Rotate on the wheel and spin it in the desired direction. If this is a wheel of fortune type wheel you'd want to determine the distance the wheel must travel and lerp the speed of the wheel so it starts fast and slows down as it approaches the desired location. Seems odd to know the result before you spin the wheel, might be better to just assign a random force to the wheel and let angular drag make the result be whatever the result is. Less math!
     
  4. Zalstadt

    Zalstadt

    Joined:
    Jul 2, 2018
    Posts:
    2
    Code (CSharp):
    1.        Quaternion oldRot = Quaternion.identity;
    2.        while (transform.rotation.x <= -0.05f || transform.rotation.x >= 0.05f)
    3.         {
    4.             gameObject.transform.Rotate(new Vector3(-degrees, 0, 0));
    5.  
    6.             yield return new WaitForFixedUpdate();
    7.         }
    8.  
    9.         while (oldRot != transform.rotation)
    10.         {
    11.             oldRot = transform.rotation;
    12.             transform.rotation = Quaternion.RotateTowards(transform.rotation, tmp, 1.0f);
    13.             yield return new WaitForFixedUpdate();
    14.         }
    So this ended up working as a solution for me. It could be smoothed out but Instead of checking on Euler rotation x equaling zero I checked on the Quaternion version which proved to have a better result.
     
    Last edited: Mar 20, 2019