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

Question Lerp Rotation 360 degrees without Wrap?

Discussion in 'Scripting' started by DanStainesTorrens, Apr 9, 2023.

  1. DanStainesTorrens

    DanStainesTorrens

    Joined:
    Mar 4, 2023
    Posts:
    1
    So I'm using Lerp to move a GameObject from one waypoint to another and I'd like to rotate that object 360 degrees as it moves along the vector.

    Here's the code I'm using. It works fine, until I set the targetRot to 360. At that point, the rotation "wraps" and the object doesn't rotate at all. If I set it to, say, 180 degees, it works fine.

    Code (CSharp):
    1. public class LerpExample : MonoBehaviour
    2. {
    3.     [SerializeField] Transform start;
    4.     Vector2 startPos;  
    5.     [SerializeField] Transform end;
    6.     Vector2 endPos;
    7.     float currentRot;
    8.     float targetRot;  
    9.  
    10.     public float cP = 0f;
    11.     public float tP = 1f;
    12.     public float speed = 0.5f;
    13.  
    14.     void Start()
    15.     {
    16.         startPos = start.transform.position;
    17.         endPos = end.transform.position;
    18.         currentRot = start.eulerAngles.z;
    19.         targetRot = end.eulerAngles.z;
    20.     }
    21.  
    22.     void Update()
    23.     {
    24.         if(cP == tP)
    25.         {
    26.             if(tP == 0){tP = 1;}
    27.             else{tP = 0;}
    28.         }
    29.         cP = Mathf.MoveTowards(cP, tP, Time.deltaTime * speed);
    30.         transform.position = Vector2.Lerp(startPos, endPos, cP);
    31.  
    32.         float angle = Mathf.Lerp(currentRot, targetRot, cP);
    33.         transform.eulerAngles = new Vector3(0, 0, angle);
    34.     }
    35. }
    How would I stop the wrapping and have the object rotate a full 360 degrees as it travels from startPos to endPos?

    Thanks!
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,160
    Any reason you're writing all the code above instead of just using a tweener like LeanTween / DOTween?

    Or else just make yourself a hard-wired animation, throw away ALL that code. :)
     
  3. chemicalcrux

    chemicalcrux

    Joined:
    Mar 16, 2017
    Posts:
    713
    Mathf includes "Angle" versions of functions that work correctly for degrees -- e.g. Mathf.LerpAngle.
     
    halley likes this.