Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

partial rotation follow causing problems when rotation goes from 180 to -180

Discussion in 'Scripting' started by aasmundwt, Jan 28, 2020.

  1. aasmundwt

    aasmundwt

    Joined:
    Sep 30, 2019
    Posts:
    5
    So in this case where the rotation multiplier is 0.5, when it goes from 180 to -180 the rotation of the object that is being rotated goes from 90 to -90 while I need it to go from 90 to 91, 92, etc. and vise versa, so it needs to work in the opposite direction too.

    Code (CSharp):
    1. [SerializeField] private Transform _target;
    2.     [SerializeField] private float _multiplier = 0.5f;
    3.  
    4.  
    5.     void Update()
    6.     {
    7.         Vector2 directionToTarget = _target.position - transform.position;
    8.  
    9.         float angle = Mathf.Atan2(directionToTarget.y, directionToTarget.x) * Mathf.Rad2Deg;
    10.  
    11.         Quaternion targetRotation = Quaternion.Euler(0f, 0f, angle * _multiplier);
    12.         transform.rotation = targetRotation;
    13.      
    14.     }
     
  2. StarManta

    StarManta

    Joined:
    Oct 23, 2006
    Posts:
    8,741
    You'll need to start tracking the rotation as a difference, rather than as an absolute. When you see that the difference from the previous frame has changed by more than 180 degrees, you can add or subtract 360 - that way it will interpret 179 to -179 as +2 rather than -358. The number resulting from that would be safe to multiply by any factor.
    Code (csharp):
    1. float lastAngleSrc = 0f;
    2. float myAngle= 0f;
    3. void Update() {
    4. //using your original code here
    5.     Vector2 directionToTarget = _target.position - transform.position;
    6.     float angle = Mathf.Atan2(directionToTarget.y, directionToTarget.x) * Mathf.Rad2Deg;
    7. //now we figure out the difference
    8.     float angleDiff = angle - lastAngleSrc;
    9.     if (angleDiff > 180f) angleDiff -= 360f;
    10.     if (angleDiff < -180f) angleDiff += 360f;
    11.     myAngle += angleDiff * _multiplier;
    12.     lastAngleSrc = angle;
    13. //and now we're back to your logic
    14.     Quaternion targetRotation = Quaternion.Euler(0f, 0f, myAngle * _multiplier);
    15.     transform.rotation = targetRotation;
    16. }
     
    aasmundwt likes this.
  3. aasmundwt

    aasmundwt

    Joined:
    Sep 30, 2019
    Posts:
    5
    thanks
     
    Last edited: Jan 28, 2020