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. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

Question How to make an object rotate to a direction over time

Discussion in '2D' started by TheLouisChild, Jan 25, 2023.

  1. TheLouisChild

    TheLouisChild

    Joined:
    Jul 10, 2021
    Posts:
    3
    Hi, I am trying to create a top down rts style controller where the player clicks somewhere on the map and a game object will rotate over time to face point where the user clicked before moving towards it. I have the movement issue down but I can't seem to get the object to rotate properly.

    The rotation code I have looks like this.
    Code (CSharp):
    1. private void FixedUpdate()
    2. {
    3.     Vector3 dir = (_activeCommand - _rigidBody.position).normalized;
    4.  
    5.     if (dir != Vector3.zero && _isTurning)
    6.     {
    7.         Quaternion targetQuat = Quaternion.LookRotation(dir);
    8.         _rigidBody.transform.rotation = Quaternion.RotateTowards(_rigidBody.transform.rotation, targetQuat, playerTurnSpeed * Time.fixedDeltaTime);
    9.         _rigidBody.transform.rotation = Quaternion.Euler(0, 0, _rigidBody.transform.eulerAngles.z);
    10.  
    11.         if (Mathf.Abs(_rigidBody.transform.eulerAngles.z - _targetAngle) < 0.5f)
    12.         {
    13.             _rigidBody.transform.rotation = Quaternion.Euler(0, 0, _targetAngle);
    14.             _isTurning = false;
    15.         }
    16.     }
    17. }
    For certain movements it will rotate to the correct direction as intended, in other cases it will rortate to be exactly 180 degrees the wrong way. I assume this is going to be how I handle euler angles, but not sure where I am going wrong.

    Anyone know what's going wrong?
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,958
    Smoothing movement between any two particular values:

    https://forum.unity.com/threads/beginner-need-help-with-smoothdamp.988959/#post-6430100

    You have currentQuantity and desiredQuantity.
    - only set desiredQuantity
    - the code always moves currentQuantity towards desiredQuantity
    - read currentQuantity for the smoothed value

    Works for floats, Vectors, Colors, Quaternions, anything continuous or lerp-able.

    The code: https://gist.github.com/kurtdekker/fb3c33ec6911a1d9bfcb23e9f62adac4

    Obviously you would use Mathf.MoveTowardsAngle() as noted in the above link.
     
    TheLouisChild likes this.
  3. TheLouisChild

    TheLouisChild

    Joined:
    Jul 10, 2021
    Posts:
    3
    Took a little bit of tweaking on my end, but that works perfectly. Thanks
     
    Kurt-Dekker likes this.