Search Unity

Question Accelerate rotation angle to value in x seconds

Discussion in 'Scripting' started by c8theino, Apr 16, 2021.

  1. c8theino

    c8theino

    Joined:
    Jun 1, 2019
    Posts:
    20
    This is more of a math question than a coding question. My current version takes 1.4 seconds to reach the desired rotation angle, and it should reach it in 1 second. I believe that the reason for that is that it currently accelerates to speed of 90 in 1 second and not to rotation angle of 90. Since I am not that good in math, I have no idea how I need to adjust the acceleration calculation. I am unable to find any solution to this from the forums nor from anywhere else.

    NOTE: I need to adjust the rotation angles manually, I am not able to use any existing functions, like for example transform.Rotate(), since in my complete version the rotation direction can change at any time and the rotation also has deceleration value.

    This is a very simplified version of what I have (it only rotates the z axis to one direction and runs once on start):
    Code (CSharp):
    1. private float accelerationInSeconds = 1;
    2. private float maxRotation = 90f;
    3. private float speed = 0;
    4. private float axis = 1;
    5.  
    6. private bool rotate = true;
    7. private float acceleration;
    8.  
    9. void Start() {
    10.     // Calculate acceleration (this calculation should be changed)
    11.     acceleration = maxRotation / accelerationInSeconds;
    12. }
    13.  
    14. void Update() {
    15.     if (rotate) {
    16.         // Accelerate
    17.         speed += axis * (acceleration * Time.deltaTime);
    18.  
    19.         // Calculate next rotation position
    20.         Vector3 rotationVector = transform.rotation.eulerAngles;
    21.         rotationVector.z += speed * Time.deltaTime;
    22.  
    23.         // Rotate object
    24.         transform.rotation = Quaternion.Euler(rotationVector);
    25.  
    26.         // Check if rotation has gone over the max rotation
    27.         if (rotationVector.z >= maxRotation) {
    28.             rotationVector.z = maxRotation;
    29.             speed = 0;
    30.             rotate = false;
    31.         }
    32.     }
    33. }
    Thanks in advance for anyone who can help!